0

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???);
}
5
  • 3
    First what??? is Object. Second what??? is whatever you are adding. Commented Dec 9, 2015 at 22:58
  • 1
    Due to type erasure, this isn't very possible. (it depends how you got that Class<T>) Commented Dec 9, 2015 at 22:58
  • 1
    Btw m is undefined, when you try to call invoke. Commented Dec 9, 2015 at 23:00
  • So @Dima, if I passed in a List.class , calling clazz.getDeclaredMethod("add", Object.class) would work? And for the second part, if I added a String object, would T element be an instance of List<String> ? Commented Dec 9, 2015 at 23:05
  • 1
    element is an instance of List. There are no generics in runtime. Commented Dec 9, 2015 at 23:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The argument type is unused and unnecessary. What you have is just a really verbose way of doing public static <T> List<T> makeList() { return new ArrayList<T>(); }
Oh yeah. I copied the OP's method spec and ended up not needing the type parameter, which I didn't notice. Good catch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.