简体   繁体   English

通过List <>重载Java方法

[英]Overload java method by List<>

I have the code, where methods is overlays with List<> arguments 我有代码,方法是用List<>参数覆盖

RetrunType1 func(List<Type1> arg);
ReturnType2 func(List<Type2> arg);

and Type1!=Type2, but that code compile and work fine on jdk1.6.0_45. 和Type1!= Type2,但是该代码可以在jdk1.6.0_45上编译并正常工作。 I know that this sample don't compile and work. 我知道此示例无法编译和运行。 How I can understand that? 我怎么能理解?

This is due to type erasure . 这是由于类型擦除引起的 The generic type parameters do not follow through to the byte code, so if the overloading you suggest would be legal, you would end up with a name collision in the byte code: 泛型类型参数不会遵循字节码,因此,如果您建议的重载是合法的,则最终会在字节码中造成名称冲突:

ReturnType1 func(List arg);
ReturnType2 func(List arg);

The solution is to use different names for the functions. 解决方案是为函数使用不同的名称。

The reason it worked in Java 6 was due to a bug that was fixed in Java 7. 它之所以能够在Java 6中运行,是因为Java 7中已修复了一个错误

The problem here is something called type erasure which you can read about here . 这里的问题是所谓的类型擦除,您可以在此处阅读。 The short version is however, that the Java compiler will remove the generic arguments so as to make the byte code compatible to previous Java versions. 然而,简短的版本是Java编译器将删除通用参数,以使字节代码与以前的Java版本兼容。 So both methods have the signature 所以这两种方法都有签名

RetrunType1 func(List arg);
ReturnType2 func(List arg);

So to Java those functions look pretty much the same. 因此对于Java而言,这些功能看起来几乎相同。

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

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