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?
You cannot access protected methods directly from outside class. It can only be accessed from within the class or inherited classes. To access this from outside, you will have to create a public method in the child class that calls the protected method of the parent.
super() in Java In Java, a child class inherits its parent's fields and methods, meaning it also inherits the parent's constructor. Sometimes we may want to modify the constructor, in which case we can use the super() method, which acts like the parent constructor inside the child class constructor.
Child or subclasses are classes that will inherit from the parent class. That means that each child class will be able to make use of the methods and variables of the parent class.
The answer is yes.
You need to use getMethod(String name, Class<?>... parameterTypes)
instead of getDeclaredMethod
If the inherited function is private
, you can use:
clazz.getSuperclass().getDeclaredMethod(String name, Class<?>... parameterTypes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With