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.
– Maniero
The title says one thing, but the running text says another.
– Jefferson Quesado
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.
– Marcelo Pedrazzani
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.
– Dherik