Java 反射 : invoking inherited methods from child class

标签 java inheritance reflection nosuchmethoderror

在我的应用程序中,我有以下结构:

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);
     }
}

在上面的调用中,当我从 ChildClass 的对象调用 method1 时,它抛出 java.lang.NoSuchMethodException

在实际场景中,ParentClass 有数百个方法,它们像主存储库一样工作,我们为每个客户端创建单独的 ChildClass 并覆盖客户端特定更改的方法。

有没有办法从子类对象中调用父类的方法(不被覆盖)?

最佳答案

您需要使用 getMethod(String name, Class<?>... parameterTypes)而不是 getDeclaredMethod

关于Java 反射 : invoking inherited methods from child class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42901445/

相关文章:

c++ - 防止切片的惯用方法?

java - 请参阅有关调用方法的 java 注释

ios - 如何检查对象是否具有存储属性?

c# - 需要在不知道对象是什么类型的情况下转换为对象

java - 处理 try catch block 内的 MalformedURLException 异常

java - 无法检索 urlencoded 变音符号。 [解决方案: use UTF8]

c# - 在 C# 中的每个派生类中都有一个更具体的接口(interface)

database - 将两个完全不同的类作为一个类

java - OpenOffice API - 表的最佳宽度选项(所有列)

java - 需要像指向 JTable (Java) 的指针之类的东西