Lombok alternatives for clear code without getters/setters/toString/constructors [closed]

岁酱吖の 提交于 2019-12-20 09:58:54

问题


Do you know any Lombok alternatives ? Using Lombok we can forget about messing classes with getters and setters and toString. I want to use it in my project, however I wonder if there are any better alternatives?

I am using Java 1.7 and cannot change to 1.8.


回答1:


I'm afraid, there's no alternative unless you want to switch to something like Scala or are happy with a smaller set of features like those provided by AutoValue.

While AutoValue is probably the best you can get with pure Java, it offers

  • @Getter
  • @AllArgsConstructor
  • @EqualsAndHashCode
  • @ToString
  • @Builder

but it misses

  • @Wither
  • toBuilder
  • @Setter
  • @Delegate
  • @ExtensionMethod
  • and some more features I don't use.

While I strongly agree that immutability is a virtue, it sometimes isn't applicable. Anyway, Lombok tries hard to support immutability, it even integrates with Guava's immutable collections, and you can write

@Builder @Getter public final class Sentence {
    private final boolean truthValue;
    @Singular private final ImmutableList<String> words;    
}

and use it like

Sentence s = Sentence.builder().truthValue(true)
    .word("Lombok").word("is").word("cool").build();
assertEquals(3, s.getWords().size());

Note: I'm not the author, so I can say it's cool.

For immutables, @Wither and toBuilder are pretty cool. The former allows you to create a copy differing by a single field and the latter gives you a builder starting with the current values and suitable for changing multiple fields. The following two lines are equivalent:

o.withA(1).withB(2)
o.toBuilder().a(1).b(2).build()

Both Lombok and AutoValue use some magic. The magic of the latter is the standard annotation processing, so it's pretty robust. It has some disadvantages as listed on page 27. I'd add the fact that some AutoValue_foo gets generated which I didn't order.

Lombok uses some black magic and thus is much more fragile, but it offers more and works pretty well.




回答2:


"Better" is fairly contentious here, but one alternative is AutoValue, available here. This presentation explains some of the differences between AutoValue and e.g. Lombok.

In particular, AutoValue emphasizes immutability (a good thing, generally!) and a minimum of extralinguistic magic (very different from Lombok).



来源:https://stackoverflow.com/questions/21741166/lombok-alternatives-for-clear-code-without-getters-setters-tostring-constructors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!