2015년 10월 29일 목요일

자바 익명 클레스에서 외부 변수 참조

리스너 같은 경우에서 상위 클래스나 다른 클래스의 변수를
참조 하고 싶을때 사용하는 방법


int myVariable = 1;

...

myButton.addActionListener(new ActionListener() {
    private int anonVar;
    public void actionPerformed(ActionEvent e) {
        // How would one access myVariable here?
        // It's now here:
        System.out.println("Initialized with value: " + anonVar);
    }
    private ActionListener init(int var){
        anonVar = var;
        return this;
    }
}.init(myVariable)  );




new 하고 새로 생성하게되면 인스턴트가 놓이게 되는 것을 이용하여
함수도 호출 할수 있음을 이용함...
매력넘침..


댓글 없음:

댓글 쓰기