Aar*_*run 2 java private data-members
可能重复:
Java中是否可以通过反射访问私有字段
有没有办法让我们可以在java中调用类的私有数据成员,可以在类外访问.我希望这是一个棘手的问题银行.尽管我的java体验,我认为这是可能的,但我不知道如何做到这一点.
1)如果SecurityManager允许,您可以使用反射执行此操作
class B {
private int x = 2;
}
public class A {
public static void main(String[] args) throws Exception {
Field f = B.class.getDeclaredField("x");
f.setAccessible(true);
f.get(new B());
}
}
Run Code Online (Sandbox Code Playgroud)
2)在内部课程的情况下
class A {
private int a = 1;
class B {
private int b = 2;
private void xxx() {
int i = new A().a;
};
}
private void aaa() {
int i = new B().b;
}
Run Code Online (Sandbox Code Playgroud)
根据java语言规范,第3版:
6.6.8 Example: private Fields, Methods, and Constructors
A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses.
Run Code Online (Sandbox Code Playgroud)
您可以reflection在java中使用访问私有字段.理想情况下,您应该使用公共setter和getter方法从类外部访问此类数据(正如其他人发布的那样)
| 归档时间: |
|
| 查看次数: |
43270 次 |
| 最近记录: |