[英]Methods with two Generics in Java
I have a problem and want to ask you guys why this code doesn't work and how can I make it work without deleting generics or Methods. 我有一个问题,想问你们为什么这个代码不起作用,以及如何在不删除泛型或方法的情况下使它起作用。 I think it's because the method cannot be overloaded since S and T can be the same type, is it correct?
我认为这是因为S和T可以是同一类型,所以该方法不能重载,对吗? But I still have no idea know how to make it work.
但是我仍然不知道如何使它工作。 Thank you!
谢谢!
public class GenericFail<S,T> {
public void doAnything(S sValue){
System.out.println("Doing anything with S");
}
public void doAnything(T sValue){
System.out.println("Doing anything with T");
}
}
The generic type is erased after compilation. 泛型类型在编译后被擦除。 So the two
doAnything()
method have the same signature : 因此,两个
doAnything()
方法具有相同的签名:
doAnything(Object object)
since S
and T
don't explicitly derive from a more specific type. 因为
S
和T
并未明确衍生自更具体的类型。
To solve the problem : either change the method name to have two distinct names or make S
and T
derive from a specific type such as : 解决该问题的方法:将方法名称更改为具有两个不同的名称,或者使
S
和T
源自特定类型,例如:
public class GenericFail<S extends CharSequence, T extends Number> {
Because of type erasure the two methods have the same signature, thats not allowed in java. 由于类型擦除,这两种方法具有相同的签名,这在Java中是不允许的。 You need to use a workaround.
您需要使用解决方法。
Your options: 您的选择:
Change the erasure of the generic types by adding type bounds 通过添加类型界限来更改通用类型的擦除
class GenericFail<S extends Number, T extends Collection<?>>
Change the names of the methods, eg have doSAnything
and doTAnything
更改方法的名称,例如具有
doSAnything
和doTAnything
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.