为什么我无法将类型参数显式传递给泛型Java方法? [英] Why can't I explicitly pass the type argument to a generic Java method?

查看:160
本文介绍了为什么我无法将类型参数显式传递给泛型Java方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个Java函数:

I have defined a Java function:

static <T> List<T> createEmptyList() {
    return new ArrayList<T>();
}

调用它的一种方式如下所示:

One way to call it is like so:

List<Integer> myList = createEmptyList(); // Compiles

为什么我不能通过显式传递泛型类型参数来调用它? :

Why can't I call it by explicitly passing the generic type argument? :

Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why?

我得到错误表达式的非法开始从编译器开始。

I get the error Illegal start of expression from the compiler.

推荐答案

当java编译器无法自行推断静态方法的参数类型时,使用完全限定的方法名称:Class。 < Type> method();

When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class . < Type > method();

Object list = Collections.<String> emptyList();

这篇关于为什么我无法将类型参数显式传递给泛型Java方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆