开发者

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 hav开发者_如何学Goe 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.


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.


The following works for me:

package test;
import java.util.List;
import static test.ListUtils.createList;

public class ListConsumer {
    public static void main(String[] args) {
        List<Integer> list = createList();
        List<String> list2 = createList();
    }
}


You can't. This is a design flaw in the syntax of the Java language. Scala, which is a newer statically typed language on JVM, fixes this. (This is how you'd make that call in Scala: val intList: List[Int] = creatList[Int]()).


I believe Mindas has already demonstrated that this should work with inference, your syntax is just a bit off. However I would recommend you have a look at Google Guava, they have this exact method and several other useful ones available. No sense re-inventing the wheel :)


As far as I've read, a shortcoming of the static import mechanism is that you must specify the calling object/class if you wish to provide formal parameters. Mindas is correct, when there are no arguments, the type inference mechanism will use the type that the function return value is being assigned to. The trick comes when you are providing arguments however. If you wish to avoid having to specify the calling object/class you can type hint through a cast of the arguments as such:

public static <E> E foo(E e) {}

Number n = foo((Number)3);

With the type hint, the type inference will return an object of type Number, instead of Integer as it would have reasoned otherwise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜