tags:

views:

132

answers:

2

I'm attempting to call a constructor method that looks like:

public static SomeWrapper<T> method(Class<T> arg);

When T is an unparameterized type like String or Integer, calling is straightforward:

SomeWrapper<String> wrapper = method(String.class);

Things get tricky when T is a parameterized type like List<String>. The following is not valid:

SomeWrapper<List<String>> wrapper = method(List<String>.class);

About the only thing I could come up with is:

List<String> o = new ArrayList<String>();
Class<List<String>> c = (Class<List<String>>) o.getClass();
SomeWrapper<List<String>> wrapper = method(c);

Surely there is an easier way that doesn't require the construction of an additional object?

+4  A: 
cletus
Yeah, I understand that there is no such thing as List<String>.class. I'm mostly just looking for some sort of syntactic sugar to pass in a List.class object when the type erasure needs to be List<String> in the end. Unfortunately, I don't control the method (it's a library method in Mockito), so changing the method isn't an option.
Brian Ferris
@Brian If you're talking about the `mock()` method, you can only do `List list = mock(List.class)` without a parameterized type. You can choose to cast it to a `List<String>` but this will, as I'm sure you know, generate a warning. I tend to use the `@SuppressWarnings("unchecked")` annotation on the method for this. The same issue comes up a lot in JPA. There is no syntactic sugar for this.
cletus
I'm actually using ArgumentCaptor. As far as I understand, this cast is not allowed (suppress warnings or not). ArgumentCaptor<List<String>> predictionCapture = (ArgumentCaptor<List<String>>) ArgumentCaptor.forClass(List.class);
Brian Ferris
A: 

Could this be of any help? http://www.javaruntype.org/

Gabriel Ščerbák