简体   繁体   中英

Access an object from another class in private method

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM