[英]How to define JSON with Lombok in properties: @JsonPropertyOrder and @JsonIgnore (JAVA)
[英]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.