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? 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(Object object)
since S
and T
don't explicitly derive from a more specific type.
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 :
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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.