mardi 19 janvier 2016

Figure the parameter to pass of the invocation of a method via reflection

I have a set of classes that implement generic interface such as:

public inteface CustomGenerator {  
   Object generate(Reader r);  
} 

These classes can process the parameter accordingly and generate the response in the expected type.
I have a base class that I need to populate. To populate class I use these custome generator classes and reflection.

public static void copy(CustomClass target, String type, Reader reader) {  
   Object input = CustomGenerators.get(type).generate(reader); 
   String setter = setterNames.get(type);   
   Method m = target.getClass().getMethod(setter, input.getClass);  
   m.invoke(target, input);   
}  

}

Exception handling omitted for clarity. This works but I want the address the following:
Problem:
Some of the types passed in don't have a custom generator to parse them because they are essentially primitives and 1) I didn't want to create many small classes just to do something trivial like Integer.valueOf(reader.nextString());
On the other side, when I call the target.getClass().getMethod I need the parameter type and I need to handle the cases of primitive values.
So I would need somehow to figure out here:
target.getClass().getMethod(setter, input.getClass); what is the second parameter I need to pass.

How can I cleanly fix this?





Aucun commentaire:

Enregistrer un commentaire