Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic classes in generic methods

Tags:

java

generics

I'm using the Mockito mock framework to mock a generic class in Java. The usage of the framework seems to be pretty clear from the documentation, I didn't find an example for mocking generic classes. The mock framework contains the following method:

public static <T> T mock(Class<T> classToMock) {
    ...
}

I have a generic type IState<StateId, Event> and I want to instantiate it using the above method. I tried the following:

IState<StateId, Event> mockState = Mockito.mock(IState.class);

I get the following warning for this code:

Type safety: The expression of type IState needs unchecked conversion to conform to IState<StateId,Event>

I think I know what the problem is. The mock method returns a type of IState, but the variable I'm assigning to is a specialized type IState<StateId, Event>, so I somehow need to tell it that the class I am creating is specifically IState<StateId, Event>, but I don't know what the syntax for this is. I tried the following ones, but they all gave syntax errors.

IState<StateId, Event> mockState = Mockito.mock(IState<StateId, Event>.class);
IState<StateId, Event> mockState = Mockito.mock(IState.class<StateId, Event>);
like image 796
petersohn Avatar asked Nov 12 '22 07:11

petersohn


1 Answers

Generics in java are implemented via type erasure. It means that parameterized classes are checked by the compiler, but at runtime all classes are "raw" (for retrocompatibility reasons). A consequence of this is that there is only one Class object representing IState, and not an infinite number of classes corresponding to all possible parameters.

To disable the warning, add @SuppressWarning("unchecked") just before the line.

like image 87
WilQu Avatar answered Nov 14 '22 21:11

WilQu