Java – How To Invoke Parent Class Methods using Java Reflection

This post shows you how to call or invoke methods of parent/super class by using Java Reflection.

Let’s look at the below code example to see how it works.

ReflectionExample.java
package com.bytenota;

import java.lang.reflect.Method;


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

class B {
    public void sayGoodbye() {
        System.out.println("Goodbye");
    }
}


public class ReflectionExample {
    
    public static void main(String[] args) throws Exception {
        // create a new instance 
        Object aInstance = Class.forName("com.bytenota.A").getDeclaredConstructor(null).newInstance(null);
        
        // invoke sayGoodbye() method of super class B
        Method method = aInstance.getClass().getSuperclass().getDeclaredMethod("sayGoodbye", null);
        method.invoke(aInstance, null);
    }
    
}

In the above code, we create class A that extends class B, then use reflection to invoke sayGoodbye() method of class B from an instance of class A.

Output:

Goodbye

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x