Reputation: 11
Suppose I have a generic class
public class A<T> {}
Then , A is instantiated with B and C, with C extends from another class D :
public class B {}
public class C extends D {}
A<B> b = new A<>();
A<C> c = new A<>();
What I'm trying to do is creating a method which accepts A<T> a
as a parameter. However, I plan to overload the function, so that the instance whose type parameter extends from D can be handled differently.
public class X {
public static void fun(A<?> a) {}
public static void fun(A<? extends D> a) {}
}
However, the code above cannot be compiled, since it seems that the second func
also bounds to Object
. My question would be how to handle such case ? Should I just use instanceof
, or is there any neater way to accomplish this ?
Edit : I'm trying to create a function which can handle specific classes with overloading, but there's a catch-all function that will handle other non-specified classes, since I cannot know in advance what classes are going to be used for the type parameter
Upvotes: 1
Views: 303
Reputation: 159086
it seems that the second
func
also bounds toObject
That is incorrect.
Because of type erasure, the generics are removed, so they both become:
public static void fun(A a) {}
public static void fun(A a) {}
Solution: Don't use overloading, use different method names.
Upvotes: 2