简体   繁体   English

泛型是否绑定了Java中方法签名的一部分?

[英]Is generics bound part of method signature in Java?

I realized today that this compiles and runs fine: 我今天意识到这个编译并运行良好:

public class Test {
    public static <T> T handle(T val) {
        System.out.println("T");
        return val;
    }

    public static <T extends String> T handle(T val) {
        System.out.println("T extends String");
        return val;
    }
}

The two handle methods has the same name, and same number and type ( ? ) of parameters. 两个handle方法具有相同的名称,相同的数字和类型( ? )的参数。 The only difference is that the second handle method has a stricter generic bound. 唯一的区别是第二个handle方法具有更严格的通用边界。 IDE does not complain at all, and the code compiles fine. IDE根本没有抱怨,代码编译得很好。 At run time method is selected as expected - eg Test.handle("this is a string") will call into the second method and Test.handle(10) will invoke the first one. 在运行时方法按预期选择 - 例如, Test.handle("this is a string")将调用第二个方法, Test.handle(10)将调用第一个方法。

Is generics bound considered part of the method signature? 泛型绑定是否被认为是方法签名的一部分? or is it a method overload resolution magic? 或者它是一种方法重载决议魔术?

Generics offer compile-time type-safety; 泛型提供编译时类型安全性; At runtime, your methods erase to the following: 在运行时,您的方法将擦除以下内容:

public static Object handle(Object val) {
    System.out.println("T");
    return val;
}

public static String handle(String val) {
    System.out.println("T extends String");
    return val;
}

Due to method overloading, handle(String) will be called when passing a String , and handle(Object) will be called when passing any other Object (keep in mind String is final and can have no children). 由于方法重载,在传递String时将调用handle(String) ,并且在传递任何其他Object时将调用handle(Object) (请记住String是final并且没有子节点)。

The bound of the generics is considered. 考虑了泛型的界限。

In the first case, the bound is Object; 在第一种情况下,绑定是Object; in the second case, the bound is String. 在第二种情况下,绑定是String。

When types are erased, the bound is used in place of the type variable, so these become simply an overload taking (and returning) Object and String parameters, respectively. 当擦除类型时,使用绑定代替类型变量,因此这些只是分别过载(和返回)Object和String参数。

Nothing wrong with that. 没有错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM