且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从外部类访问内部类的私有属性?

更新时间:2022-10-18 15:07:25

编译器生成访问内部类私有成员的方法。如果您编译示例代码并检查字节码,您会发现它就像是这样编写的:

  public class OuterClass {

public class InnerClass {
private int privateProperty = -2;
static int access $ 002(InnerClass obj,int value){
obj.privateProperty = value;
返回值;
}
}

public static void main(String [] args){
OuterClass oc = new OuterClass();
InnerClass ic = oc.new InnerClass();
InnerClass.access $ 002(ic,-98);
}
}

此行的转换

  ic.privateProperty = -98; 

进入方法调用:

  InnerClass.access $ 002(ic,-98); 

以及静态方法的创建 InnerClass.access $ 002 由编译器完成。静态方法(我的编译器名为 access $ 002 )是您已阅读的合成setter方法的示例。因此,这两个类的字节码不违反Java的访问规则。


I have read this concept in respect to static inner class : ViewHolder declared as inner class inside the adapter of ListView to enhance the performance of getView().

Consider the below class

public class OuterClass{

    public class InnerClass{
        private int privateProperty= -2;
    }

    public static void main(String[] args) {
        OuterClass oc = new OuterClass();
        InnerClass ic = oc.new InnerClass();
        ic.privateProperty = -98;
    }
}

If inner class contains private properties and an object of inner class is created inside a method of outer class then the inner class private properties can be accessed directly using . 'dot' operator.

I have read somewhere that the private properties of the inner class are accessed using synthetic setter getter methods from outer class

I want to clear my concept regarding the same.

The compiler generates method to access private members of an inner class. If you compile your example code and examine the bytecode, you will find that it is as if it were written like this:

public class OuterClass{

    public class InnerClass{
        private int privateProperty= -2;
        static int access$002(InnerClass obj, int value) {
            obj.privateProperty = value;
            return value;
        }
    }

    public static void main(String[] args) {
        OuterClass oc = new OuterClass();
        InnerClass ic = oc.new InnerClass();
        InnerClass.access$002(ic, -98);
    }
}

This conversion of the line

ic.privateProperty = -98;

into the method call:

InnerClass.access$002(ic, -98);

together with the creation of the static method InnerClass.access$002 is done by the compiler. The static method (named access$002 by my compiler) is an example of a "synthetic setter method" you have read about. As a result, the bytecode for the two classes do not violate Java's access rules.