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???);
}
what???isObject. Secondwhat???is whatever you are adding.Class<T>)mis undefined, when you try to callinvoke.List.class, callingclazz.getDeclaredMethod("add", Object.class)would work? And for the second part, if I added a String object, wouldT elementbe an instance ofList<String>?elementis an instance ofList. There are no generics in runtime.