Wildcard generics problem
Brought to you by:
tammofreese
Following code is not compiling:
public class SomeTest
{
public static interface A
{
public Class<?> get();
}
@Test
public void testSomething()
{
A mock = EasyMock createMock(A.class);
EasyMock.expect(mock.get()).andReturn(String.class); replay(mock);
}
}
Error message is as follows:
The method andReturn(Class<capture#2-of ?="">) in the type
IExpectationSetters<Class<capture#2-of ?="">> is not applicable for the arguments
(Class<String>)
To make it valid I need to change Class<?> to raw type Class. Then it works.
Obviously following code is perfectly valid:
public class StringA implements A
{
public Class<?> get() { return String.class; }
}
Logged In: YES
user_id=893525
Originator: NO
You are facing a special generic feature called type erasure. You can't set a wildcard to a fix type. For instance you can't do
Class<String> c = a.get();
There's no way that I know for EasyMock to workaround this. To have something more flexible, you can type like this:
public <T> Class<T> get();
Typed like this you could have done this:
expect(mock.<String>get()).andReturn(String.class);
In your case, the only solution is
expect((Class) mock.get()).andReturn(String.class);
You'll get a compilation warning but that's the best you can do.
This Tracker item was closed automatically by the system. It was
previously set to a Pending status, and the original submitter
did not respond within 14 days (the time period specified by
the administrator of this Tracker).