Java Reflection : invoking inherited methods from child class
Asked Answered
C

2

6

In my application I have following structure :

public class ParentClass{
    public void method1()
    {....}

    public void method2()
    {....}

    public void method3()
    {....}

    public void method4()
    {....}

    public void method5()
    {....}
}

public class ChildClass extends ParentClass{
    public void method3()
    {....}

    public void method4()
    {....}
}


//I have exported the above class in a jar file.
//--------------------XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX---------------------------

public class TestClass{
     public static void main(String args[]) {
        String jarpath = "jar path of the above class"
        File jarFile = new File(jarpath);
        URLClassLoader classLoader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()},Thread.currentThread().getContextClassLoader());
        Class<?> dynamicClass = (Class<?>) classLoader.loadClass("packageName.ChildClass");
        Constructor<?> cons = dynamicClass.getConstructor();
        classObject = cons.newInstance();
        Method method = obj2.getClass().getDeclaredMethod("method1",null);
        method.invoke(obj2);
     }
}

In the above call when I invoke the method1 from the object of ChildClass it throws java.lang.NoSuchMethodException.

In actual scenario ParentClass have hundreds on methods which work like main repository and for each Client we create separate ChildClass and override the methods for client specific changes.

Is there any way to invoke the method (which are not overridden) of parent class from the child class object?

Chiropodist answered 20/3, 2017 at 10:40 Comment(1)
That's because you are using getDeclaredMethod() but your ChildClass does not declare the method. Your ParentClassdoes. Consider using getMethod instead.Barbera
U
13

You need to use getMethod(String name, Class<?>... parameterTypes) instead of getDeclaredMethod

Urushiol answered 20/3, 2017 at 10:43 Comment(0)
M
2

If the inherited function is private, you can use:

clazz.getSuperclass().getDeclaredMethod(String name, Class<?>... parameterTypes);
Melesa answered 7/1, 2020 at 21:52 Comment(1)
Thank you. This is exactly what I was looking forHeer

© 2022 - 2024 — McMap. All rights reserved.