Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke Super class methods using Reflection

Tags:

java

I have 2 classes, say A & B:

Class A extends B {
    public void subClassMthd(){
        System.out.println("Hello");
    }
}

Class B {
    public void printHelloWorld {
        System.out.println("Hello");
    }
}

Now, I am using reflection to invoke the methods on Class A. I would also like to invoke the printHelloWorld method present in Class B.

I tried using

Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Method superClassmthd = classAInstance.getClass()
    .getSuperclass().getMethod("printHelloWorld", null);
superClassmthd.invoke(classAInstance);

Also tried as

Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Class superClazz = Class.forName(classAInstance.getClass().getSuperclass().getName());
Object superclassInstance = superClazz.newInstance();
Method superClassmthd = superclassInstance.getMethod("printHelloWorld", null);
superClassmthd.invoke(superclassInstance );

But none of them work; they throw an InstantiationException.

What am I doing wrong here?

like image 875
Vivek Avatar asked Jan 22 '13 09:01

Vivek


2 Answers

Try this:

Method mthd = classAInstance.getClass().getSuperclass().getDeclaredMethod("XYZ");
mthd.invoke(classAInstance)

The difference is using getDeclaredMethod(), which gets methods of all visibilities (public, protected, package/default and private) instead of getMethod(), which only gets methods with public visibility.

like image 108
Bohemian Avatar answered Oct 30 '22 07:10

Bohemian


What is the visibility of the methods you want to call (public, private etc). If you want to see methods which you cannot call directly, you should use getDeclaredMethod().

Also, what the the constructors of your classes like? InstantiationException indicates that you are having trouble getting an instance of class A (or B).

I have the following code and it works:

A.java

import java.lang.reflect.Method;

public class A extends B {

    public static void main(String[] args) throws Exception {
        A classAInstance = new A();
        Method mthd = classAInstance.getClass().getSuperclass().getMethod("XYZ", null);
        mthd.invoke(classAInstance);
    }

}

B.java

public class B {

    public void XYZ() {
        System.out.println("done");
    }

}
like image 41
NickJ Avatar answered Oct 30 '22 08:10

NickJ