如何将参数传递给匿名类?

Lew*_*wis 143 java anonymous-class

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

int myVariable = 1;

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

有没有办法让侦听器访问myVariable或传递myVariable而不将侦听器创建为实际的命名类?

Ada*_*ski 328

是的,通过添加一个返回'this'的初始化方法,并立即调用该方法:

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)  );
Run Code Online (Sandbox Code Playgroud)

不需要"最终"声明.

  • 因为myButton.addActionListener(...)需要一个ActionListener对象作为调用其方法时返回的对象. (11认同)
  • 为什么`init()`函数必须返回`this`?我真的没有得到语法. (7认同)
  • 哇......太棒了!我已经厌倦了创建一个`final`引用对象,所以我可以将信息输入到我的匿名类中.谢谢你的分享! (4认同)
  • 更简单: private int anonVar = myVariable; (2认同)

Mat*_*lis 76

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

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

编辑:正如Peter所指出的,您还可以将参数传递给匿名类的超类的构造函数.

  • 匿名类使用使用其父级的构造函数.例如`new ArrayList(10){}` (20认同)
  • 匿名类可以具有Instance Initializers,它可以作为匿名类中的无参数构造函数.它们以与字段赋值相同的顺序执行,即在"super()"之后和实际构造函数的其余部分之前执行.`new someclass(){fields; {initializer}字段; methods(){}}`.它有点像静态初始化器,但没有static关键字.http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.6 (4认同)

aav*_*aav 27

是.你可以捕获变量,对内部类可见.唯一的限制是它必须是最终的

  • 实例变量通过`this`引用,这是最终的. (8认同)

ada*_*shr 20

像这样:

final int myVariable = 1;

myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // Now you can access it alright.
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 13

这将是神奇的

int myVariable = 1;

myButton.addActionListener(new ActionListener() {

    int myVariable;

    public void actionPerformed(ActionEvent e) {
        // myVariable ...
    }

    public ActionListener setParams(int myVariable) {

        this.myVariable = myVariable;

        return this;
    }
}.setParams(myVariable));
Run Code Online (Sandbox Code Playgroud)


Rob*_*ell 8

http://www.coderanch.com/t/567294/java/java/declare-constructor-anonymous-class所示,您可以添加实例初始化程序.它是一个没有名称并首先执行的块(就像构造函数一样).

看起来他们也在为什么java实例初始化器讨论过实例初始化程序如何与构造函数不同?讨论了与构造函数的差异.


Ala*_*ack 7

我的解决方案是使用一个返回已实现的匿名类的方法.常规参数可以传递给方法,并且可以在匿名类中使用.

例如:(从某些GWT代码处理文本框更改):

/* Regular method. Returns the required interface/abstract/class
   Arguments are defined as final */
private ChangeHandler newNameChangeHandler(final String axisId, final Logger logger) {

    // Return a new anonymous class
    return new ChangeHandler() {
        public void onChange(ChangeEvent event) {
            // Access method scope variables           
            logger.fine(axisId)
        }
     };
}
Run Code Online (Sandbox Code Playgroud)

对于此示例,将使用以下引用新的匿名类方法:

textBox.addChangeHandler(newNameChangeHandler(myAxisName, myLogger))
Run Code Online (Sandbox Code Playgroud)

或者,使用OP的要求:

private ActionListener newActionListener(final int aVariable) {
    return new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Your variable is: " + aVariable);
        }
    };
}
...
int myVariable = 1;
newActionListener(myVariable);
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

87455 次

最近记录:

8 年,7 月 前