I have two classes (A and B) with identical methods (foo):
public class A {
public String foo() {
return "A said foo";
}
}
public class B {
public String foo() {
return "B said foo";
}
}
I want to make generic class which can call this method. But I have two ideas how to do this in runtime and haven't ideas about compile time:
check for type and cast to A or B.
Get method.
My example of generic which calls getMethod:
public class Template<T> {
private T mT;
public Template(T t) {
mT = t;
}
public String bar() {
String result = "no result";
try {
Method m = mT.getClass().getMethod("foo", null);
result = (String)m.invoke(mT);
} catch (Exception e) {
result = e.toString();
e.printStackTrace();
}
return result;
}
}
Are there another way how to do it? I am looking for something like this:
public class Template<T extends A | B> {
...
}
Note, that I am not a creator of classes "A" and "B".