[solved] Re: accessing subclasse methods and fields with introspection / reflection
Ooops, my fault.
Well, the fault of the code hierarchy in fact. I found a way to fix it.
Thank you a lot for the example. I had to test it before I could believe it
worked with your code and not with mine ;-)
The problem was that some of the classes I had were simulating inheritance
with delegating calls to an internal field ('has a' relation) Here is the
skeleton of the structure I had:
////////////////////////////////////////////////
import java.lang.reflect.Method;
interface IA {
public String[] methodIA();
public void printMethods();
}
interface IB {
public String[] methodIB();
}
interface IC {
public String[] methodIC();
}
abstract class MandatoryLegacy {
public abstract void mMandatoryLegacy();
}
/** this class is the only one really implementing IA*/
class AA implements IA {
public String[] methodIA(){return null;}
public void printMethods() {
Method[] lMethods = getClass().getMethods();
for (int i=0; i<lMethods.length; i++) {
System.out.println("- " + lMethods[i].getName());
}
}
}
/** Here is the *fake* implementation of IA */
abstract class A extends MandatoryLegacy implements IA {
AA mAA = new AA();
public void mMandatoryLegacy() {}
public String[] methodIA() {return mAA.methodIA();}
public void printMethods() {mAA.printMethods();}
}
abstract class B extends A implements IB {
public String[] methodIB() {return null;}
}
class C extends B implements IC {
public String[] methodIC() {return null;}
}
public class testReflect {
public static void main(String[] args) {
C mC = new C();
mC.printMethods();
}
}
////////////////////////////////////////////////
It outputs:
////////////////////////////////////////////////
- *printMethods*
- *methodIA*
- hashCode
- getClass
- wait
- wait
- wait
- equals
- notify
- notifyAll
- toString
////////////////////////////////////////////////
See, all the methods IB, IC etc. are missing. Anyway, my problem is now
solved. Thank you
The fix was to add a 'specialPrintMethods(Class iClass)' method to AA and
use it in A So A becomes:
abstract class A extends MandatoryLegacy implements IA {
AA mAA = new AA();
public void mMandatoryLegacy() {}
public String[] methodIA() {return mAA.specialPrintMethods(getClass());}
public void printMethods() {mAA.printMethods();}
}