Bhu*_*anK 4 java reflection inheritance 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);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的调用中,当我调用它method1的对象ChildClass时抛出它java.lang.NoSuchMethodException.
在实际场景中ParentClass有数百个方法与主存储库一样工作,对于每个客户端,我们创建单独的ChildClass并覆盖客户端特定更改的方法.
有没有办法从子类对象调用父类的方法(没有被覆盖)?