javagenericsstatic-import

How can I call a Generic method with a type, when it's statically imported?


I found that you can call a generic method with a special Type, e.g.:

suppose we have a generic method:

class ListUtils {
    public static <T> List<T> createList() {
        return new ArrayList<T>();
    }
}

we can call it like:

List<Integer> intList = ListUtils.<Integer>createList();

But how can we call it when it's statically imported? e.g.:

List<Integer> intList = <Integer>createList();

this does not work.


Solution

  • You can't. You'd have to reference it using the class name.

    It seems that having:

    void foo(List<String> a) {}
    

    and calling foo(createList()) does not infer the correct type. So you should either explicitly use the class name, like ListUtils.createList() or use an intermediate variable:

    List<String> fooList = createList();
    foo(fooList);
    

    Finally, guava has Lists.newArrayList(), so you'd better reuse that.