利用匿名类直接new接口对象

今天在学习GUI的时候,给Button添加监听时,留意到了这样一段代码

button.addMouseWheelListener(new MouseWheelListener() {
            @Override
            public void mouseWheelMoved(MouseWheelEvent arg0) {
                System.out.println("操作了滚轮");
            }
        });

可以看到是直接newMouseWheelListener 接口,很纳闷为什么可以直接 new 接口。
接口直接用 new 操作了
观察到 bin 目录下面生成的 .class 文件中多了一个这样的文件 Demo$1.class ,而源文件是 Demo.class 。 打开Demo$1.class可以发现里面是我们new对应接口所写的程序。

// Compiled from Demo.java (version 1.7 : 51.0, super bit)
class com.guigu.event.Demo$1 implements java.awt.event.MouseWheelListener {

  // Field descriptor #8 Lcom/guigu/event/Demo;
  final synthetic com.guigu.event.Demo this$0;

  // Method descriptor #10 (Lcom/guigu/event/Demo;)V
  // Stack: 2, Locals: 2
  Demo$1(com.guigu.event.Demo arg0);
     0  aload_0 [this]
     1  aload_1 [arg0]
     2  putfield com.guigu.event.Demo$1.this$0 : com.guigu.event.Demo [12]
     5  aload_0 [this]
     6  invokespecial java.lang.Object() [14]
     9  return
      Line numbers:
        [pc: 0, line: 1]
        [pc: 5, line: 16]
      Local variable table:
        [pc: 0, pc: 10] local: this index: 0 type: new com.guigu.event.Demo(){}

  // Method descriptor #22 (Ljava/awt/event/MouseWheelEvent;)V
  // Stack: 2, Locals: 2
  public void mouseWheelMoved(java.awt.event.MouseWheelEvent arg0);
    0  getstatic java.lang.System.out : java.io.PrintStream [23]
    3  ldc "操作了滚轮"> [29]
    5  invokevirtual java.io.PrintStream.println(java.lang.String) : void [31]
    8  return
      Line numbers:
        [pc: 0, line: 19]
        [pc: 8, line: 20]
      Local variable table:
        [pc: 0, pc: 9] local: this index: 0 type: new com.guigu.event.Demo(){}
        [pc: 0, pc: 9] local: arg0 index: 1 type: java.awt.event.MouseWheelEvent

  Inner classes:
    [inner class info: #1 com/guigu/event/Demo$1, outer class info: #0
     inner name: #0, accessflags: 0 default]
  Enclosing Method: #42  #44 com/guigu/event/Demo.init()V
}

可以看出来java内部帮我们做了一些改变,new 的对象其实是被创建成一个Inner classes了,这样的确在某些时候简化操作。

源文件的代码:

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

public class Demo {
    public Demo(){
        init();
    }
    public void init(){
        Frame frame = new Frame();
        frame.setVisible(true);
        Button button = new Button("test");
        button.addMouseWheelListener(new MouseWheelListener() {
            @Override
            public void mouseWheelMoved(MouseWheelEvent arg0) {
                System.out.println("操作了滚轮");
            }
        });
        frame.add(button);
        frame.pack();
    }
    public static void main(String[] args) {
        new Demo();
    }
}

你可能感兴趣的:(利用匿名类直接new接口对象)