如何将参数传递给匿名类? [英] How to pass parameters to anonymous class?

查看:142
本文介绍了如何将参数传递给匿名类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以传递参数或访问外部参数到匿名类?例如:

Is it possible to pass parameters, or access external parameters to an anonymous class? For example:

int myVariable = 1;

myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // How would one access myVariable here?
    }
});

听众有没有办法访问myVariable或传递myVariable而不创建实际的监听器命名类?

Is there any way for the listener to access myVariable or be passed myVariable without creating the listener as an actual named class?

推荐答案

技术上,不,因为匿名类不能有构造函数。

Technically, no, because anonymous classes can't have constructors.

但是,类可以引用包含范围的变量。对于匿名类,这些可以是包含类的实例变量或标记为final的局部变量。

However, classes can reference variables from containing scopes. For an anonymous class these can be instance variables from the containing class(es) or local variables that are marked final.

编辑:作为Peter指出,您还可以将参数传递给匿名类的超类的构造函数。

edit: As Peter pointed out, you can also pass parameters to the constructor of the superclass of the anonymous class.

这篇关于如何将参数传递给匿名类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆