Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 784
Visus Zhao Avatar asked Nov 04 '10 10:11

Visus Zhao


People also ask

Can we use generic in static method?

Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

How do you invoke a generic method?

To call a generic method, you need to provide types that will be used during the method invocation. Those types can be passed as an instance of NType objects initialized with particular . NET types.

Can generic class handle any type of data?

A generic class and a generic method can handle any type of data.

Can you instantiate a generic type?

Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters. Cannot Use Casts or instanceof With Parameterized Types.


1 Answers

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.

like image 171
Bozho Avatar answered Oct 22 '22 12:10

Bozho