在私有方法中从另一个 class 访问一个对象
Access an object from another class in private method
如何在 Java 的私有方法中访问另一个 class 的对象?
从另一个调用私有方法的简单示例 class。
文件:A.java
public class A {
private void message(){System.out.println("hello java"); }
}
文件: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);
}
}
因为 private 仅在声明的 类 中使用,不能从其他 类 调用。如需使用,修改为protected或public.
后即可使用
通常私有方法只能从同一个 class 中访问。无法从外部访问私有方法 class。但是,有一种方法可以从外部访问私有方法 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));
}
}
如何在 Java 的私有方法中访问另一个 class 的对象?
从另一个调用私有方法的简单示例 class。
文件:A.java
public class A {
private void message(){System.out.println("hello java"); }
}
文件: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);
}
}
因为 private 仅在声明的 类 中使用,不能从其他 类 调用。如需使用,修改为protected或public.
后即可使用通常私有方法只能从同一个 class 中访问。无法从外部访问私有方法 class。但是,有一种方法可以从外部访问私有方法 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));
}
}