泛型的静态方法重载 [英] Static Method Overloading with Generics
问题描述
在我尝试创建两个静态重载方法的地方,我收到了一个编译错误。任何人都可以解释这个
public class A {
public static void a(Set< String> stringSet){}
public static void a(Set< Map< String,String>> mapSet){}
}
原因是 type erasure 。泛型没有存储在类中,它们只是编译时信息,所以在运行时,这两种方法是相同的,因此存在命名冲突。
参考
- Sun Java
教程的常规部分 - Java泛型和集合
(Book)
这三种方法实际上是相同的字节码):
public static void a(Set plainSet){}
public static void a(Set< String> stringSet){}
public static void a(Set< Map< String,String>> mapSet){}
如果你真的想要两个独立的方法,你必须提供不同的方法签名(例如不同的方法名称,一个方法的附加参数等)。
Where I try to create two static overloading methods I got an compilation error. Can anyone explain this
public class A {
public static void a(Set<String> stringSet) {}
public static void a(Set<Map<String,String>> mapSet) {}
}
The reason is type erasure. Generics are not stored in the classes, they are compile-time info only, so at runtime, the two methods are identical and hence there is a naming conflict.
Reference
These three methods are actually identical (read: they produce identical bytecode):
public static void a(Set plainSet) {}
public static void a(Set<String> stringSet) {}
public static void a(Set<Map<String,String>> mapSet) {}
If you really want to have two separate methods, you must provide different method signatures (e.g. different method names, an additional parameter for one of the methods etc.)
这篇关于泛型的静态方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!