reflecting methods of parent class
I have a class named ParentClass with a public method named getName that takes a String as a paramenter and returns a String.
If I extend ParentClass, how can I use reflection to access the getName method of the parent (super) class? I get a NoSuchMethodException if I try to get the subclass to reflect any methods it inherits from its parent.
[357 byte] By [
boyedav] at [2007-9-30 17:53:16]

What you describe seems to work just fine:import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception{
Class cls = SubClass.class;
Method m = cls.getMethod("getName", new Class[] {String.class});
System.out.println(m);
}
}
class ParentClass {
public String getName(String s) {
return s;
}
}
class SubClass extends ParentClass {
}
Also ,I modified the above example to print the method return value . It work fine.
import java.lang.reflect.Method;
public class TestReflection {
public static void main(String[] args) throws Exception{
SubClass cls = new SubClass();
Method m = cls.getClass().getMethod("getName", new Class[] {String.class});
System.out.println(m.invoke(cls,new Object[] {new String("testing name")}));
}
}
class ParentClass {
public String getName(String s) {
return s;
}
}
class SubClass extends ParentClass {}