具有泛型参数的主要方法;为什么它有效?
Main method with generic parameter; why does it work?
public static <T extends String> void main(T[] args) {
System.out.println("Hello World!");
}
我很好奇上面的代码片段是否会编译并 运行 成功,确实如此!不过,我也想知道如果把T extends String
换成T extends String & AutoClosable
会怎么样; String
没有实现 AutoClosable
,所以我没想到 运行 成功了,但它仍然可以!
public static <T extends String & AutoCloseable> void main(T[] args) {
System.out.println("This still works!");
}
所以我的问题是,为什么这仍然 运行 成功?
备注:
- 我正在使用 Java 10.0.1
进行测试
- Intellij 不能很好地使用这种方法,因为它没有将其视为程序的入口点;我还没有用其他 IDE 测试过它。
- 您还可以像使用任何其他程序一样使用命令行传递参数。
这是因为类型参数有一个界限:
<T extends String> => String
<T extends String & AutoCloseable> => String & AutoCloseable
擦除后的字节码与两种情况下的常规 main
声明相同:
public static main([Ljava/lang/String;)V
The order of types in a bound is only significant in that the erasure
of a type variable is determined by the first type in its bound, and
that a class type or type variable may only appear in the first
position.
public static <T extends String> void main(T[] args) {
System.out.println("Hello World!");
}
我很好奇上面的代码片段是否会编译并 运行 成功,确实如此!不过,我也想知道如果把T extends String
换成T extends String & AutoClosable
会怎么样; String
没有实现 AutoClosable
,所以我没想到 运行 成功了,但它仍然可以!
public static <T extends String & AutoCloseable> void main(T[] args) {
System.out.println("This still works!");
}
所以我的问题是,为什么这仍然 运行 成功?
备注:
- 我正在使用 Java 10.0.1 进行测试
- Intellij 不能很好地使用这种方法,因为它没有将其视为程序的入口点;我还没有用其他 IDE 测试过它。
- 您还可以像使用任何其他程序一样使用命令行传递参数。
这是因为类型参数有一个界限:
<T extends String> => String
<T extends String & AutoCloseable> => String & AutoCloseable
擦除后的字节码与两种情况下的常规 main
声明相同:
public static main([Ljava/lang/String;)V
The order of types in a bound is only significant in that the erasure of a type variable is determined by the first type in its bound, and that a class type or type variable may only appear in the first position.