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

Answer

I’m guessing what you are trying to do is this:

public static <T> List<T> makeList() {
   List<T> list = (List<T>) new ArrayList();
   return list;
}

//...
{
   List<String> list = makeList();
   list.add( "Howdy" );
}  

Which works as-is in Java 8. In earlier versions you may have to add @SuppressWarnings("unchecked") to the assignment.

Leave a Reply

Your email address will not be published. Required fields are marked *