lundi 20 mars 2017

Java Reflection : invoking inherited methods from child class

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?





Aucun commentaire:

Enregistrer un commentaire