简体   繁体   中英

accessing private member of member class

I have a class A, with a private member int myMember. And a class B with a private member of the class A, called myA;

That is:

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

public class B{
    private A myA;

}

I would like to be able to access:

B.myA.myMember;

but it seems I can't because myMember is private in A. The thing is, I need A to be defined as private for the purpose of the exercise (that also includes it can't be protected). Is there a way around this?

Thanks.

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

Use getters :

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

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

So now you can code :

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

Since you've stated you can't create more public methods, aka getters, you could use reflection...

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



}

If you can declare the private field as static then something like this is possible :

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

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