簡體   English   中英

Java:Lombok和unwrapping屬性

[英]Java: Lombok and unwrapping properties

我正在使用JavaFx屬性和Lombok

我最近開始使用Lombok,它使我的代碼更簡單和可讀,但我有JavaFx屬性的問題,它沒有解開它們就像我用IntelliJ生成它我得到了屬性本身的getter和一個getter for the值。 這是一個簡單的例子,解釋了我想做什么。

public class LombokAndProperties {

    public static void main(String[] args) {
        Model model = new Model();

        model.getStringProperty(); // returns the StringProperty instead of String
        model.stringProperty(); // doesn't exist -> doesn't compile

        // Expectation:
        // model.getStringProperty() <- return the String that is stringProperty.get()
        // model.stringProperty() <- return the StringProperty itself
    }


    @Getter
    private static class Model{

        private StringProperty stringProperty;

    }

}

我知道我可以使用: model.getStringProperty().get()來獲取String值,但我更喜歡直接的方式,如果它存在。

這有什么解決方案嗎?

我找到了一種方法:

public class LombokAndProperties {

    public static void main(String[] args) {
        Model model = new Model();

        model.getStringProperty(); // <- return the String that is stringProperty.getStringProperty()
        model.stringProperty(); // <- return the StringProperty itself

    }



    private static class Model{

        private interface DelegateExample {
            String getStringProperty();
        }

        @Accessors(fluent = true)
        @Getter
        @Delegate(types = DelegateExample.class)
        private StringProperty stringProperty = new StringProperty();

    }

    private static class StringProperty {
        String property = "p";

        public String getStringProperty(){
            return property;
        }
    }
}

使用@Accessor注釋,您可以操縱您的getter名稱,而@Delegate為您提供委托模式。 你可以在這里這里找到更多。 但請注意兩件事:首先,這些注釋被Lombok團隊標記為“實驗性”。 其次,對我來說這是一個非常混亂的API,所以要小心使用它。

如果這個解決方案過於復雜,我建議只采用@Accessor並創建自己的委托方法:

public class LombokAndProperties {

    public static void main(String[] args) {
        Model model = new Model();

        model.getStringProperty(); // <- return the String that is stringProperty.get()
        model.stringProperty(); // <- return the StringProperty itself

    }

    private static class Model{

        @Accessors(fluent = true)
        @Getter
        private StringProperty stringProperty;

        public String getStringProperty(){
            return stringProperty.get();
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM