Suppose I’ve got two classes A and B such that B extends A, respectively implementing method getA and getB that has the same input parameter types and same return type (but different names). In a method public static <T extends A> void print(T t) getting as input an object of type A or B, I want to call getA if the object is of type A or getB if the object is of type B.
If I could edit the code of A and B I would make them implement an interface I providing getValue() (in the implementation for A and B, getValue() would call getA() and getB() resp.), and then call this method from print(). Problem is: classes A and B are not modifiable!. No methods can be added or changed, their class hierarchy is fixed, I didn’t write their code, and I don’t have access to the source.
Note that this also applies to the cases when – for any reason – I don’t want to change the code of A and B.
Is there any way of doing so without the use of instanceof?
Here follows a solution that uses instanceof (bad!).
public class Test {
public static <T extends A> void print(T t){
if (t instanceof B)
System.out.println(((B)t).getB());
else if (t instanceof A)
System.out.println(t.getA());
}
public static class A {
public String getA(){
return "A";
}
}
public static class B extends A {
public String getB(){
return "B";
}
}
}
To extend Matt’s answer, I would consider adopting the Facade Pattern for these classes. This means you create a separate class (or two) to wrap all the functionality you require from these two classes. This includes adding a method, as Matt suggests.
The benefit is you decouple your application from an API you have no control over. You also have an opportunity to simplify the API, if you don’t require all the methods from the original libraries.