`
ruvuoai
  • 浏览: 94134 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

beanshell学习笔记(四)——scripting interface

阅读更多
由于对beanshell对接口的实现功能不是很清楚..故写下这篇不只是对是错的理解,主要是为了給自己留下学习时产生的疑问及即使的理解,为后来的梳理做个标记


对接口的实现是beanshell的强大之处之一,这个功能允许你写脚本来构建handle,listener或者一些java API的是实现

匿名内部类

可以使用标准的匿名内部类语法来实现java接口,如下
buttonHandler = new ActionListener() {
    actionPerformed( event ) { 
        print(event);
    }
};

button = new JButton();
button.addActionListener( buttonHandler );
frame(button);

上面的代码中,我们创建了个对象来实现ActionListener接口,并把生成的对象分配你变量buttonHandler,并实现actionPerformed(event),

在看下面的代码
actionPerformed( event ) {
    print( event );
}

button = new JButton("Foo!");
button.addActionListener( this );
frame( button ); 

没有实现ActionListener,直接用了'this'关键字注册监听,这就体现了beanshell的自动匹配的特性,上面的actionperformed()方法的到了实现,当有关注册监听的时候,就能自动cast,
前面讲到'this'关键字代表着他在范围的对象,所以上面的代码就可以看成整个脚本implement了actionListener接口,并在脚本中直接实现了actionPerformed()

在看下面的代码:

messageButton( message ) {
    JButton button = new JButton("Press Me");
    button.addActionListener( this );
    JFrame frame = frame( button );
 
    actionPerformed( e ) {
        print( message );
        frame.setVisible(false);
    }
}

messageButton("Hey you!");
messageButton("Another message...");


actionPerformed()方法是在messageButton()内部实现,前面有讲到,在beanshell中方法即可以看成对象,上面代码中的this正是代表着messageButton作用范围所代表的对象,你可以看成这个对象实现了ActionListener()接口

由此可以看出,beanshell在执行的过程中,会根据请求和参数以及返回值来自动匹配接口中的方法

不需要实现接口的所有的方法,只需要实现你使用的方法即可,如果使用你没有实现的方法,beanshell将抛出一个错误,
ml = new MouseListener() {
mousePressed( event ) { ... }
// handle the rest
invoke( name, args ) { print("Method: "+name+" invoked!");
}

由此实现多线程.可以如下方法直接实现
foo() {
    run() {
        // do work...
    }
    return this;
}

foo = foo();
// Start two threads on foo.run()
new Thread( foo ).start();
new Thread( foo ).start();


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics