java - 我怎样才能编写一个方法来使这段代码可重用?

标签 java javafx

我有以下代码,其中 Binding.createStringBinding(...) 部分将重复很多次,唯一的区别是使用的方法,即 getA() getB()getC()

    this.attributeA.bind(Bindings.createStringBinding(() -> {
        if(webService.getLastValue() != null){
            return webService.getLastValue().getA();
        } else{
            return "";
        }
    }, webService.lastValueProperty()));

    this.attributeB.bind(Bindings.createStringBinding(() -> {
        if(webService.getLastValue() != null){
            return webService.getLastValue().getB();
        } else{
            return "";
        }
    }, webService.lastValueProperty()));

新: 这是我想要重用的代码部分:

Bindings.createStringBinding(() -> {
            if(webService.getLastValue() != null){
                return webService.getLastValue().getB();
            } else{
                return "";
            }
        }, webService.lastValueProperty())

如何使其可重复使用?也许将其作为一个函数?

最佳答案

也许是这样的:

private Binding createBinder(final Supplier<String> lambda) {
    return Bindings.createStringBinding(() -> {
        if(webService.getLastValue() != null){
            return lambda.get();
        } else{
            return "";
        }
    }
}

称呼为

this.attributeA.bind(createBinder(() -> webService.getLastValue().getA()), webService.lastValueProperty());
this.attributeB.bind(createBinder(() -> webService.getLastValue().getB()), webService.lastValueProperty());

关于java - 我怎样才能编写一个方法来使这段代码可重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33104126/

相关文章:

java - 进度条对话框关闭后如何显示警报对话框?

带有controlsfx通知组件的javafx NullPointerException

JavaFX ChoiceBox 空选择

java ArrayList只添加一个元素

FXML 中的 JavaFX MediaView

image - 如何删除 JavaFX GridPane 中的 "ghost line"?

java - 从数组添加到 ListArray

java - 将 List<Map<Long, String>> 转换为 List<Long> Java 8

java - 使用 xsl 将 XML 传输到 CSV 期间的空行

java - Spring Jdbc模板+ MySQL = TransientDataAccessResourceException : Invalid Argument Value : Java. io.notSerializationException