带通用参数的主要方法;它为什么有效?

时间:2022-10-01 21:26:21
public static <T extends String> void main(T[] args) {
    System.out.println("Hello World!");
}

I was curious to see if the above snippet of code would compile and run successfully, and it does! However, I also wondered what would happen if T extends String was replaced with T extends String & AutoClosable; String does not implement AutoClosable, so I didn't expect this to run successfully, but it still does!

我很想知道上面的代码片段是否可以编译并成功运行,而且确实如此!但是,我也想知道如果T扩展String会被T extends String&AutoClosable替换会发生什么; String没有实现AutoClosable,所以我没想到会成功运行,但它仍然可以!

public static <T extends String & AutoCloseable> void main(T[] args) {
    System.out.println("This still works!");
}

So my question is, why does this still run successfully?

所以我的问题是,为什么这仍然成功运行?

Notes:

  • I'm testing this with Java 10.0.1
  • 我正在使用Java 10.0.1进行测试

  • Intellij doesn't play nice with this method because it doesn't see it as an entry point to the program; I haven't tested it with other IDEs.
  • Intellij对这种方法不好看,因为它不认为它是程序的入口点;我没有用其他IDE测试过它。

  • You're also able to pass arguments using the command-line just as you would with any other program.
  • 您也可以使用命令行传递参数,就像使用任何其他程序一样。

1 个解决方案

#1


31  

This is because a type parameter has a bound:

这是因为类型参数有一个绑定:

<T extends String>                  =>  String

<T extends String & AutoCloseable>  =>  String & AutoCloseable

And the bytecode after erasure is the same as for the regular main declaration in both cases:

擦除后的字节码与两种情况下的常规主声明相同:

public static main([Ljava/lang/String;)V

JLS §4.4. Type Variables:

JLS§4.4。类型变量:

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.

绑定中类型的顺序只是重要的,因为类型变量的擦除由其边界中的第一个类型确定,并且类类型或类型变量可能仅出现在第一个位置。

#1


31  

This is because a type parameter has a bound:

这是因为类型参数有一个绑定:

<T extends String>                  =>  String

<T extends String & AutoCloseable>  =>  String & AutoCloseable

And the bytecode after erasure is the same as for the regular main declaration in both cases:

擦除后的字节码与两种情况下的常规主声明相同:

public static main([Ljava/lang/String;)V

JLS §4.4. Type Variables:

JLS§4.4。类型变量:

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.

绑定中类型的顺序只是重要的,因为类型变量的擦除由其边界中的第一个类型确定,并且类类型或类型变量可能仅出现在第一个位置。