You can, if you pass in the type as a method parameter.
static <T> List<T> createEmptyList( Class<T> type ) {
return new ArrayList<T>();
}
@Test
public void createStringList() {
List<String> stringList = createEmptyList( String.class );
}
Methods cannot be genericised in the same way that a type can, so the only option for a method with a dynamically-typed generic return type -- phew that's a mouthful :-) -- is to pass in the type as an argument.
For a truly excellent FAQ on Java generics, see Angelika Langer's generics FAQ.
.
.
Follow-up:
It wouldn't make sense in this context to use the array argument as in Collection.toArray( T[] )
. The only reason an array is used there is because the same (pre-allocated) array is used to contain the results (if the array is large enough to fit them all in). This saves on allocating a new array at run-time all the time.
However, for the purposes of education, if you did want to use the array typing, the syntax is very similar:
static <T> List<T> createEmptyList( T[] array ) {
return new ArrayList<T>();
}
@Test
public void testThing() {
List<Integer> integerList = createEmptyList( new Integer[ 1 ] );
}