如何在Java中用lambda替换匿名类? [英] How do I replace an anonymous class with a lambda in Java?

查看:45
本文介绍了如何在Java中用lambda替换匿名类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码,但是IntelliJ告诉我用lambda替换匿名,但我不知道如何.谁能帮我这个?这是我的代码:

I've got this code but IntelliJ tells me to replace anonymous with lambda but I don't know how. can anyone help me with this? Here is my code:

soundVolume.valueProperty().addListener(new ChangeListener<Number>() {
    public void changed(ObservableValue<? extends Number> ov,
                     Number old_val, Number new_val) {
        main.setSoundVolume(new_val.doubleValue());
        main.getMediaPlayer().setVolume(main.getSoundVolume());
    }
}); 

推荐答案

通常,类似这样:

methodUsingYourClass(new YourClass() {
    public void uniqueMethod(Type1 parameter1, Type2 parameter2) {
        // body of function
    }
});

被替换为

methodUsingYourClass((parameter1, parameter2) -> {
    // body of function
});

可以从用法中推断出参数的类型,但是在某些情况下,指定它们很有用.上例中的这部分

The types of the parameters can be inferred from usage, but there may be situations where specifying them is useful. This part from the above example

(parameter1, parameter2) -> {

如果您决定明确指定类型,则将成为此

would become this, if you decided to specify the types explicitly

(Type1 parameter1, Type2 parameter2) -> {

对于您的特定示例,您可以使用:

For your specific example, you can use:

soundVolume.valueProperty().addListener(
    (ov, old_val, new_val) -> {
        main.setSoundVolume(new_val.doubleValue());
        main.getMediaPlayer().setVolume(main.getSoundVolume());
    }
);

注意,仅当匿名类具有一个方法时,才可以用lambda替换该匿名类.如果匿名类具有更多方法,则无法进行替换.

Note the replacement of an anonymous class with lambda is possible only if the anonymous class has one method. If the anonymous class has more methods then the substitution is not possible.

来自 Oracle文档:

上一节匿名类"向您展示了如何在不给基类命名的情况下实现它.尽管这通常比命名类更简洁,但是对于只有一个方法的类,即使是匿名类也显得有些繁琐. Lambda表达式使您可以更紧凑地表示单方法类的实例.

这篇关于如何在Java中用lambda替换匿名类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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