首页 > 代码库 > 内部类 -access$000 访问私有域

内部类 -access$000 访问私有域

内部类:

package innerClass;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

/**
 * Created by admin on 2017-3-29.
 */
public class InnerClassTest {

    public static void main(String[] args) {
        TalkingClock clock = new TalkingClock(1000,true);
        clock.start();
        JOptionPane.showMessageDialog(null,"Quit program?");
        System.exit(0);
    }

}
class TalkingClock{
    private int interval;
    private boolean beep;

    public TalkingClock(int interval, boolean beep) {
        this.interval = interval;
        this.beep = beep;
    }

    public void start(){
        ActionListener listener = new TimePrinter();
        Timer t = new Timer(interval,listener);
        t.start();
    }
class TimePrinter implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(new Date());
        if (beep){
            System.out.println("beep");
        }
    }
}

}

非内部类:

package innerClass;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;

/**
 * Created by admin on 2017-3-29.
 */
public class InnerClassTest {

    public static void main(String[] args) {
        TalkingClock clock = new TalkingClock(1000,true);
        clock.start();
        JOptionPane.showMessageDialog(null,"Quit program?");
        System.exit(0);
    }

}
class TalkingClock{
    private int interval;
    private boolean beep;

    public TalkingClock(int interval, boolean beep) {
        this.interval = interval;
        this.beep = beep;
    }

    static boolean access$000(TalkingClock talkingClock){
        return talkingClock.beep;
    }
    public void start(){
        ActionListener listener = new TimePrinter(this);
        Timer t = new Timer(interval,listener);
        t.start();
    }

}
class TimePrinter implements ActionListener{

    private TalkingClock outer;

    public TimePrinter(TalkingClock clock) {
        outer = clock;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(new Date());
        if (TalkingClock.access$000(outer)){
            System.out.println("beep");
        }
    }
}

1.内部类可以访问该类定义所在作用域中数据,包括私有。是因为内部类的对象有一个隐式引用,他指向了创建它的外部类对象。外部类的引用在构造器中设置,构造器的参数为外部类引用。
2.内部类一种编译器现象,与虚拟机无关。编译器会把内部类翻译成用$(美元符号)分隔外部类名与内部类名的常规文件。编译器为了引用外部类,会生成一个附加的实例域this$0(名字是有编译器合成的,在自己的代码中不能引用它)。

3.内部类被翻译成名字怪异的常规类,对于域来说,每个域会自动生成一个静态方法access$000(或access$0),该方法接受所属类对象为参数,返回值传给域。可以利用这个在B类中调用A类的私有方法。

内部类 -access$000 访问私有域