Presumably, you have a finite number of classes implementing this method, and you can directly link them. Therefore you do not need to speculate. Reflection is evil.
Say you have a set of classes using a method:
public class LibA { public Program getProgram() { return program; } ... };
public class LibB { public Program getProgram() { return program; } ... };
...
Then you just need instanceof / cast pairs. You can put this in a method, so you only need to do this once.
public static Program getProgram(Object obj) {
if (obj instanceof LibA) {
return ((LibA)obj).getProgram();
} else if (obj instanceof LibB) {
return ((LibB)obj).getProgram();
} else {
throw new IllegalArgumentException(obj+" doesn't have a known getProgram");
}
}
Alternatively, you can use an adapter:
public interface ProgramContainer {
Program getProgram();
...
}
public class LibAContainer implements ProgramContainer {
private final LibA libA;
public LibAContainer(LibA libA) {
this.libA = libA;
}
public Program getProgram() {
return libA.getProgram();
}
...
}
source
share