Generic Static Methods in Java

Generic Static Methods in Java

As shown in the following code, if we use generic types in the foo method, there would be an error, i.e., the compiler cannot resolve the symbol K, V and T.

1
2
3
4
5
public class GenericsDemo {
public Map<K,V> foo(T t) {
return null;
}
}

generic_method_1

In this case, as the foo method is an instance method(which belongs to this) of the GenericsDemo class, we can declare GenericsDemo as a generic class:

generic_method_2


Now if we change the foo method to a static method, there would be another error:

1
2
3
4
5
public class GenericsDemo<K,V,T> {
public static Map<K,V> foo(T t) {
return null;
}
}

generic_method_3

To fix this, we can use a generic type declaration after the keyword static:

generic_method_4