Here to Learn.
Here to Learn.

Reputation: 693

Trying to reflect a method which accepts a generic type

I have a method add which adds a generic object (i.e. T) into an List. I want to unit test this method.

public static <T> List<T> add(List<T> list, T t) {
    if(list == null) return null;
    if(t == null) return list;

    List<T> outputList = new ArrayList<T>(list);
    outputList.add(t); // append item into list

    return outputList;
}

I am trying to get the Method and test it. I have written following code snippet to obtain the method (which i know is not correct).

Class myClass = Myclass.class;
Class<List<T>> clazz = (Class<List<T>>) Class.forName("java.util.ArrayList");
Method myObjectMethod = myClass.getMethod("add", ...) // i need to identify T's class

Certain trail-error attempts lead me to NoSuchMethod exceptions.

Can anybody help me in identifying this method? any pointers to rectify the above code?

Thanks!

Upvotes: 2

Views: 118

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198481

clazz should probably be List.class, not ArrayList.class. You have to use the exact raw type used in the method definition.

Upvotes: 3

Related Questions