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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值