mercredi 9 décembre 2015

Java newInstance of Generic Class

I am working with Java Generic classes (in this example, these are the Collection classes), and Reflection. I would like to be able to use reflection to take in a Class, check if it is an instance of a List, and then invoke the add method to it.

However, I've faced some difficulties in trying to put as the parameters to invoke the method call, and getting the declared method (shown where I put-what???). Both of those method parameter calls, require an object of type Class<?> which is the parameter type of needed for the add methods being invoked, which I don't know, since T itself is a generic.

Any help is appreciated! I apologize if the question is unclear, I tried the best I could to clarify.

 static <T> void TestACollection(Class<T> clazz) {
     T element=clazz.newInstance();
     if(element instanceof List<?>)
     Method m=clazz.getDeclaredMethod("add", what???  ); 
     m.invoke(element, what???);
         }





Aucun commentaire:

Enregistrer un commentaire