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);
}
}