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