【问题标题】:What is the proper way to pass 'this' to an inline overridden method of a new object? [duplicate]将“this”传递给新对象的内联重写方法的正确方法是什么? [复制]
【发布时间】:2013-11-05 15:04:13
【问题描述】:

我使用了一个局部变量来存储this,以便使其可以在内联覆盖中访问,但对此并不满意。有没有更优雅的方式来做到这一点?

public class Tree extends Plant {
    public Tree() {
        timeline = new Timeline(new KeyFrame(Duration.millis(40), new EventHandler<ActionEvent>() {
        final Plant tree = this; // <---- here
            @Override
            public void handle(ActionEvent actionEvent) {

                tree.setA(5); // <---- and here
            }
        }));

        timeline.setCycleCount(Timeline.INDEFINITE);
    }
}

【问题讨论】:

  • 使用Tree.this

标签: java


【解决方案1】:

您应该使用Tree.this。由于您正在尝试访问另一个类(即EventHandler)中有关Tree 对象的信息,因此需要对this 进行限定,以便编译器知道您在说什么。

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多