Question

I am trying to invoke EasyMock.isA(Class<T>) on a List<MyType>. Is there a way to do it without warnings?

I've tried the following:

isA(List<MyType>.class);  // doesn't compile
isA(List.<MyType>class);  // syntax error on tokens (MyType), misplaced construct
isA(List.class);          // This gives a warning: Type safety: The expression of type List needs unchecked conversion to conform to List<MyType>

EDIT:

Jakub HR gave the correct answer. However, for my particular situation where I require this for EasyMock, I can simply use

EasyMock.<List<MyType>>anyObject()
Was it helpful?

Solution

From Effective Java:

There are two minor exceptions to the rule that you should not use raw types in new code, both of which stem from the fact that generic type information is erased at runtime. You must use raw types in class literals. The specification does not permit the use of parameterized types (though it does permit array types and primitive types). In other words, List.class, String[].class, and int.class are all legal, but List<String>.class and List<?>.class are not.

OTHER TIPS

You can get it as below:

Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

Due to type parameters erasure in JVM, you cannot check it (unless you use a custom generic List class which also stores inside an actual Class<?> object of corresponding type (which will have to be provided manually))
This is because at run time there is no way to know generic type parameters — List<String>, List<MyType>, etc. all "get erased" to List<Object> (or just List — no difference) at run time. Maybe you also want to read a more deep example out of the web

The suggested/accepted answer is not quite correct. Here is a more complete answer:

myMock.myMeth(isA(List.class)); // #1 fails if arg == null, warnings myMock.myMeth(EasyMock.<List<MT>> anyObject()); // #2 succeeds even when arg == null myMock.myMeth(anyObject()) // #3 same as #2

myMock.myMeth(EasyMock.<List<MT>> notNull()); // #4 same as #1, no warnings! myMock.myMeth(notNull()); // #5 prob same as #1, less informative

So if you really want the same behavior as isA(), use notNull() rather than anyObject(). Note that, when using either anyObject() or notNull(), you're really depending on the compiler to have ensured that the called code did in fact pass in a proper List. If you somehow managed to 'fake' some other object into the call (nearly impossible), EasyMock is not going to catch it with anyObject() or notNull().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top