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

Asked

Viewed 456 times

1

Hello,

I need to invoke a method via reflection,

Method.invoke(Objeto, arg);
  • Object -> Object created from Class.newInstance()
  • Arg -> is the value I want to pass. And I know it’s a String.

But the method parameter I don’t know, and if the parameter is something other than an error string.

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

type = Method.getParameterTypes()[0]

The question is, how to turn 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);

    }
}
  • Why do you need it? Almost everyone you think you need really doesn’t need it and has a better solution. If you’re calling a method you don’t know, which doesn’t have a known signature it’s quite complicated to have utility. And it looks like it’s gonna create a huge complicator and it’s not even going the right way.

  • The title says one thing, but the running text says another.

  • Mineiro, there really is something better, but in a newer version of a library I use, however I can not update. What I’m trying to do is sort of bind, where I pass a Cláss, of the object, for example person, and a map<String,String> of the attributes and values to fill the object via set method, and then return that complete object to the application. If there is a better way I’m open to suggestions. Thank you.

  • Hello, Marcelo. Can you post what you tried so far and which error gives? It was not very clear what you want to do. As Jefferson says, the title doesn’t match the text of the question either.

1 answer

0

I’ve 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 the polymorphism you can always pass Object by parameter that the method will know what to do.

If you want to take a look at some APIS that I created with reflection just access: https://github.com/RUSHyoutuber/System/tree/master/src/rush/apis

Browser other questions tagged

You are not signed in. Login or sign up in order to post.