Java generics and class literals

Java generics and class literals

Recently I stumble upon more problem with generics and class literals. I wanted to use Mockito ArgumentCaptor to capture List<Long> argument. As we know there is nothing like List<Long>.class so how to create properly parametrized type?

Simple attempt does not work

ArgumentCaptor<List<Long>> captor = (ArgumentCaptor<List<Long>>) ArgumentCaptor.forClass(List.class);

and ends with compiler error “Cannot cast from ArgumentCaptor<List> to ArgumentCaptor<List<Long>>”.

Stackoverflow helped at the end. Solution is not nice but works (of course you got type-safety warning but there is no other way)

ArgumentCaptor<List<Long>> captor = ArgumentCaptor.forClass((Class<List<Long>>)(Class)List.class);

Add a comment

*Please complete all fields correctly