I have 2 classes e.g. A and B.
These classes have a couple of getter/setter methods with the same name.
Now in the code I do the following:
if(obj.getClassName().equals(A.class.getName())){
A a = (A) obj;
String result = a.getInfo();
}
else if(obj.getClassName().equals(B.class.getName())){
B a = (B) obj;
String result = a.getInfo();
}
I was wondering if there is a way to call the getInfo avoiding the if statements.
Note: I can not refactor the classes to use inheritence or something else.
I was just interested if there is a trick in java to avoid the if statements.
Unless you want to use reflection, no. Java treats two types which happen to declare the same method (
getInfo()) as entirely separate, with entirely separate methods.If you’ve got commonality, you should be using a common superclass or a common interface that both of them inherit. You’ve tagged the question “design-patterns” – the pattern is to use the tools that the language provides to show commonality.
As Eng.Fouad shows, using
instanceofis simpler anyway – and better, as it means your code will still work with subclasses ofAorB.You can isolate this ugliness, of course, by putting it in a single place – either with a facade class which can be constructed from either an
Aor aB, or by having a single method which performs this check, and then calling that from multiple places.