Reputation: 200
There are two classes A and B which have similar methods. How to write a generic method that takes either one of the class object as argument and will be able to call the methods of that class.
Edit : I do not have control over class A, B. I get them only as arguments. So i cannot modify add them.
public class methods {
public static void main(String[] args) {
new methods().getName(new B());
new methods().getName(new A());
}
private <T> void getName(T obj){
// obj.getName()
}
}
class A {
String name = "ClassA";
public void getName(){
System.out.println(name);
}
}
class B {
String name = "ClassB";
public void getName(){
System.out.println(name);
}
}
Upvotes: 0
Views: 124
Reputation: 2058
If the two classes do not implement a common interface, you could use reflection, but this is not type safe (you won't get any compilation errors if A or B no longer support getName()
and reflection is much slower than calling a method directly.
You could also implement two adapters that share an interface and use those (with generics):
interface Wrapper {
String getName();
}
class WrapperA implements Wrapper {
final private A a;
public WrapperA(A wrapped) {
this.a = wrapped;
}
@Override public String getName() {
return a.getName();
}
}
Upvotes: 2
Reputation: 4912
Below solution uses instanceof operator
in the generic method to reach your output.
public static void main(String[] args){
new methods().getName(new B());
new methods().getName(new A());
}
private <T> void getName(T obj) {
if(obj instanceof B){
((B) obj).getName();
}
else{
((A) obj).getName();
}
}
Upvotes: 1