I am working with JavaFx properties and Lombok
I started recently using Lombok, it makes my code much simpler and readable, but I have the issue with JavaFx properties, it doesn't unwrap them like I would generate them with IntelliJ I get a getter for the property itself and a getter for the value. Here is a simple example with explanation what I want to do.
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;
}
}
I know that I can use like: model.getStringProperty().get()
to obtain the String
value, but I would prefer the direct way if it exists.
Does any solution exist for this?
I've found a way:
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;
}
}
}
With @Accessor
annotation you can manipulate your getter name, while @Delegate
gives you a delegation pattern. You can find more here and here . However notice two things: first, those annotations are marked as "experimental" by Lombok team. Second, to me this is a quite confusing API, so use it carefully.
If this solution is too complicated, I would suggest to adopt only @Accessor
and creating your own delegate method:
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();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.