java - 为什么使用类型参数调用非参数化方法不会出错?

标签 java generics

我有以下 Java 程序,我原以为它不会编译,但它编译了:

class Test {
    public static void f() {
    }

    void m() {
            Test.<String>f();
    }
}

为什么javac允许以这种方式调用非参数化方法?

我的Java编译器版本是:javac 1.7.0_75

最佳答案

显式类型参数会被忽略。

这在 JLS, Section 15.12.2.1 中有说明:

  • If the method invocation includes explicit type arguments, and the member is a generic method, then the number of type arguments is equal to the number of type parameters of the method.

This clause implies that a non-generic method may be potentially applicable to an invocation that supplies explicit type arguments. Indeed, it may turn out to be applicable. In such a case, the type arguments will simply be ignored.

关于java - 为什么使用类型参数调用非参数化方法不会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28584336/

相关文章:

java - 从网站 Api 获取数据到 Android 应用程序

java - JPA的AttributeConverter和Hibernate的ColumnTransformer在属性加解密方面的区别

java - 将日期从 "2009-12 Dec"格式转换为 "31-DEC-2009"

C# 泛型列表联合问题

java - 在 Java 中创建通用数组

c# - .NET Generic 集合在多线程环境中是否更慢

java - 有没有办法在 Java 中将字符串(逐个字符)转换为其 ASCII 值?

java - 将我的自定义 http header 添加到 Spring RestTemplate 请求/扩展 RestTemplate

c# - 在 C# 中,我可以编写一个通用函数来返回 null 或将值作为字符串返回吗?

swift - Swift 中的通用类型别名