访问成员类的私有成员

时间:2013-09-08 18:37:42

标签: java

我有一个A类,私人成员是myMember。还有一个B级,有一个A级私人成员,名为myA;

那是:

public class A{
    private int myMember;
    ...
}

public class B{
    private A myA;

}

我希望能够访问:

B.myA.myMember;

但似乎我不能,因为myMember在A中是私有的。事实是,我需要将A定义为私有用于练习(也包括它无法保护)。有办法解决这个问题吗?

感谢。

4 个答案:

答案 0 :(得分:6)

public class A {

private int myMember;

public int getMyMember() {
    return myMember;
}

public void setMyMember(int myMember) {
    this.myMember = myMember;
}

}


public class B{

private A myA;

public B() {
    myA = new A();
    myA.setMyMember(0);
    int a = myA.getMyMember();
}
}

答案 1 :(得分:3)

使用getters:

public class A {
    private int myMember;
    public getMyNumber() {
        return myNumber;
    }
}

public class B {
    private A myA;
    public A getA() {
        return myA;
    }
}

所以现在你可以编码:

B b = new B(); 
b.getA().getMyMember();

答案 2 :(得分:2)

既然你已经说过你不能创建更多的公共方法,即getter,你可以使用反射......

public class A{
    private int myMember;
    ...
}

public class B{
    private A myA;

    private int get(){
        try {
             Field field = myA.getClass().getDeclaredField("myMember");
             field.setAccessible(true);
             return (int) field.get(myA);
        catch (Exception e){
             //Something went wrong, the field doesn't exist or a security exception
             return null; //or return some "error number" like -10
        }
    }



}

答案 3 :(得分:1)

如果您可以将私有字段声明为静态,则可能出现以下情况:

public class A {
    private int myMember;
}

public class B {
    public static void main (String[] args) {
        int myMember = new A() {
            public int getPrivate() {
                return myMember;
            }
        }.getPrivate();
        System.out.print("\n\t Id : " + myMember);
    }
}