Every time I feel like I know all the Java syntax there is, I learn something new
Let’s say you have a class with a static constructor that returns a map, and that map is typed and does fancy things, but you still want to use generics from wherever you are using the Map.
public class MyClass {
public static final <K,V> Map<K,V> createMyMap() {
...
return map;
}
}
If you are like me, you hate hate hate casting to generics, but you are forced to do that or have a big ugly @SuppressWarnings("unchecked") on the method that you access this method.
@SuppressWarnings("unchecked")
function Map<String, Object> getMyMap() {
return MyClass.createMyMap();
}
Well not anymore!. Today I just learned (by looking through some Java source code) that you can assign generics on your static calls by using the following syntax.
function Map<String, Object> getMyMap() {
return MyClass.<String, Object>createMyMap();
}
Just put the generics right after the period and before the method name. Easy.
I learned this while trying to figure out why java.util.Collections has static fields EMPTY_LIST, EMPTY_SET, and EMPTY_MAP, and also static methods emptyList(), emptySet, and emptyMap. It says right in the code, “Unlike this method, the field does not provide type safety”.
Comments