Creating a new object, and populating its properties, using Java Reflection

0

Hello,

I need to invoke a method via reflection,

Method.invoke(Objeto, arg);
  • Object - > object created from Class.newInstance ()
  • arg - > It's the value I want to spend. And I know it's a String.

But the Parameter of the method I do not know, and if the parameter is something other than an Error String.

Then to know the type of the parameter, I look for it through reflection

type = Method.getParameterTypes()[0]

The question is how to transform the String arg variable into an Object of type type?

public static Object bindClass(Class c, Map<String, String> param) {
   //Novo objeto do tipo Class 
   Object newInstance = c.newInstance(); 

   for(String key : param.keySet()) {
       String value = param.get(Key);
       String nomeMetodo = "set" + key;
       Method method = null;

       for(Method m : newInstance.getClass().getDeclaredMethods()){
            if(m.getName().equals(nomeMetodo)){
                    method = m;
                    break;
            }
        }

        Class type = method.getParameterTypes()[0];


       //Fazer um CAST de value(String) para type 


       //Aqui é necessário passar um 'value' do mesmo tipo do método invocado, e nem sempre é o tipo String 
       method.invoke(newInstance, value);

    }
}
    
asked by anonymous 30.11.2018 / 21:04

1 answer

0

I have worked with reflection for a while, whenever I used reflection I used objects of type Object to pass by parameter, as you know all classes extend the Object class so thanks to polymorphism you can always pass Object by parameter that method you will know what to do.

If you want to take a look at some APIS I've created with reflection only access: link

    
27.12.2018 / 14:44