Reputation: 23
How do I access an object from another class in private method in Java ?
Simple example to call private method from another class.
File: A.java
public class A {
private void message(){System.out.println("hello java"); }
}
File: MethodCall.java
import java.lang.reflect.Method;
public class MethodCall{
public static void main(String[] args)throws Exception{
Class c = Class.forName("A");
Object o= c.newInstance();
Method m =c.getDeclaredMethod("message", null);
m.setAccessible(true);
m.invoke(o, null);
}
}
Upvotes: 1
Views: 2299
Reputation: 181
Since private is used only in declared classes and it can not be called from other classes. If you want to use it, you should use it after modifying to protected or public.
Upvotes: 2
Reputation: 256
Normally Private methods can access only from within the same class. Can’t access the private methods from the outside class. However, there is a way to access the private methods from outside class.
import java.lang.reflect.Method;
public class PriavteMethodAccessTest{
public static void main(String[] args)throws Exception{
A test = new A();
Class<?> clazz = test.getClass();
Method method = clazz.getDeclaredMethod("message");
method.setAccessible(true);
System.out.println(method.invoke(test));
}
}
Upvotes: 0