I have several different POJOs that use a builder pattern, but after adding a builder for each one and generating Object.toString, Object.hashCode and Object.equals, my classes end up being around 100 lines of code. There has to be a better way to handle this. I think having some sort of a reflective builder would help out a lot, but I'm not sure this would be good practice and I'm also not sure how I'd exactly make it happen. In other words, is there a way to implement a builder like this?
A simple POJO:
public class Foo {
public int id;
public String title;
public boolean change;
...
}
Then some sort of reflective builder:
Foo = ReflectiveBuilder.from(Foo.class).id(1).title("title").change(false).build();
Short answer no. What you ask for is not possible. Reflection looks at the code at runtime and invokes methods dynamically, it cannot generate actual methods.
What you could do would be:
Foo foo = ReflectiveBuilder.from(Foo.class).
set("id", 1).
set("title", "title").
build();
This has three massive problems:
the fields are Strings - a typo causes a runtime error rather than a compile time one,
the values are Objects - the wrong type causes a runtime error rather than a compile time one, and
it would be much slower than the alternative as Reflection is very slow.
So a reflection based solution, whilst possible (see Apache Commons BeanUtils BeanMap) is not at all practical.
Long answer, if you're willing to allow some compile time magic, you can use Project Lombok. The idea behind Lombok is to generate boilerplate code from annotations using the Java annotation preprocessor system.
The really magical thing is that all IDEs, well the big 3 at least, understand annotation preprocessing and code completion will still function correctly even though the code doesn't really exist.
In the case of a POJO with a Builder you can use #Data and #Builder
#Data
#Builder
public class Foo {
public int id;
public String title;
public boolean change;
...
}
The #Data annotation will generate:
a required arguments constructor (that takes all final fields),
equals and hashCode methods that use all fields (can be configured with the #EqualsAndHashCode annotation)
a toString method on all fields (can be configured with the #ToString annotation and
public getters and setters for all fields (can be configured using the #Getter / #Setter annotations on fields).
The #Builder annotation will generate an inner class called Builder that can be instantiated using Foo.builder().
Do make sure you configure the equals, hashCode and toString methods as if you have two classes with Lombok that have references to each other then you will end up with an infinite loop in the default case as both classes include the other in these methods.
There is also a new configuration system that allows you to use, for example, fluent setters so you can more of less do away with the builder if your POJO is mutable:
new Foo().setId(3).setTitle("title)...
For another approach you can look at Aspect-oriented programming (AOP) and AspectJ. AOP allows you do chop your classes up into "aspects" and then stick them together using certain rules using a pre-compiler. For example you could implement exactly what Lombok does, using custom annotations and an aspect. This is a fairly advanced topic however, and might well be overkill.
Maybe Project Lombok (yes the website is ugly) is an option for you. Lombok injects code into your classes based on annotations.
With Lombok you use the #Data annotations to generated getters, setters, toString(), hashCode() and equals():
#Data
public class Foo {
public int id;
public String title;
public boolean change;
}
Have a look at the example on the #Data documentation section to see the generated code.
Lombok also provides a #Builder that generates a builder for your class. But be aware that this is an experimental feature:
#Builder
public class Foo {
public int id;
public String title;
public boolean change;
}
Now you can do:
Foo foo = Foo.builder()
.id(123)
.title("some title")
.change(true)
.build();
I personally use this website to create all the boilerplate code for the POJOs for me. All you need to do is to paste the JSON that you want to parse, and it will generate all the classes for you. Then I just use Retrofit to do the requests/caching/parsing of the information. Here is an example of Retrofit and POJOs in my Github account.
I hope it helps!
I created a small library CakeMold to do fluent initialization of POJOs. It uses reflection, what is certainly not fast. But can be very helpful when need to write tests.
Person person = CakeMold.of(Person.class)
.set("firstName", "Bob")
.set("lastName", "SquarePants")
.set("email", "sponge.bob#bikinibottom.io")
.set("age", 22)
.cook();
Related
Using Jackson with Lombok's #Accessors(fluent=true) requires to add #JsonAutoDetect(Visibility.Any) annotation:
#Data
#NoArgsConstructor
#Accessors(fluent=true)
public class Pojo{
private String fieldOne;
private String fieldTwo;
}
I am curious of the performance of Visibilty.Any. Does it use reflection or compile time hooks are added?
Jackson uses reflection plus caching to implement serialisation and deserialisation processes anyway. Using this annotation does not add any noticeable performance cost. For more info, take a look how it is implemented: JsonAutoDetect.java. It allows you to change default visibility configuration for fields, getters, setters, creators and constructors.
I have a use case where I don't want to use the #Builder on the class itself, so I created method based builder like this:
#Builder(builderMethodName = "carBuilder")
public static Car build(int speed, String brand){
Car car = new Car();
car.setSpeed(speed);
car.setBrand(brand);
return car;
}
But how can I handle when the given class has ton of fields (over ~20).
Should I really specify them as parameters and invoke the setters by hand?
Couldn't just lombok generate them automatically based on the type?
Currently this is not possible because Lombok avoids inspecting types from elsewhere on the classpath when processing a file.
What's your reason for not adding #Builder to the class itself? If you can describe a common use case for that, you or someone else might be able to add this ability to Lombok. However, currently I can't see any good reasons for this. Most libraries should be relatively easy to use already and if its your own code, why not just add Lombok?
Also the main reason I add #Builder is because I want my classes to be immutable - given that the actual object is still mutable here, why use builder rather than the setters?
I want to have immutable myClass objects. Good solution seams to be using #Singular annotation.
The problem is when I use this annotation the method elements() appends elements to existing list, instead of creating the new one:
Let's assume that that we have:
#Value
#Builder(toBuilder = true)
public class MyClass {
#Singular
private List<String> elemets;
}
and
MyClass.builder()
.elemets(Arrays.asList("elem1"))
.elemets(Arrays.asList("elem2"))
.build();
Without #Singular annotation we have elem2 on the list
with #Singular annotation we have both elem1 and elem2, if I want to have elem2 only I have to use clearElements() before.
Why implementation is different? Is it possible to use #Singular with my own implementation?
With #Singular annotation I cannot implement elemets(List elemets) method in MyClassBuilder class because I get: "Manually adding a method that #Singular #Builder would generate is not supported. If you want to manually manage the builder aspect for this field/parameter, don't use #Singular."
First let me say that using #Singular isn't necessarily the best solution -- it depends on your use case.
However, in most cases where you want to ensure immutability on classes that use collections, it is a good choice.
#Singular behaves the way it does because the Lombok designers decided that it's a good choice to do so. And I agree: It makes the two setter methods behave similarly; and in those rare cases where you want to reset the elements in a builder, you have the clear method.
#Singular generates pretty complex code (see https://projectlombok.org/features/BuilderSingular for an example). This is to ensure properties like efficiency and immutability (also when reusing builders to produce several objects). When you mess around with that code, you can easily violate these properties. Lombok prevents you from doing that.
If you really want to modify this aspect, you have three choices:
delombok the builder code, copy it into your class, and modify it.
Add another differently named method, like clearAndSetElements(List<String>). But that's probably even more confusing.
Remove #Singular and implement the setter methods on your own. You will have to put some effort in the implementation if you want the properties of Lombok's implementation; you can use the delomboked code as inspiration.
Is there a way to customise the generated code for #Setter?
Consider the following simple class:
#Entity
#Getter
#Setter
#NoArgsConstructor
public class MyEntity implements Serializable {
#Id private long id;
#OneToMany
private Set<AttributeColumn> columns = new HashSet<>();
public void setColumns(Set<AttributeColumn> columns) {
this.columns.clear();
this.columns.addAll(columns);
}
}
I want Lombok to generate the Setter for columns as I implemented it in the example above. This should only be done on classes annotated with #Entity and on attributes that are a Collection. The Setter for other attributes, in this example id should be generated as usual.
Is there a way to customise the generation of the Setter code depending on those criteria?
No.
No, there's no such feature and no plans for it.
As already stated in a comment, you could do it yourself, but it's not easy at all. Moreover, you'd have to decide to either hardcode the logic (simple but probable unusable for others) or interpret something like
#SetterWhen(#Or(
#Condition(annotatedWith=Entity.class),
#Condition(declaredType=Collection.class)))
which is close to impossible to implement (as this information is unavailable when Lombok runs).
Currently, all you can do is to allow on suppress the generation on a per field basis. There's no possibility to generate a different setter, however
there's a related feature: #Singular, which may or may not help you.
This isn't about a recent problem, more like one from history which I think I just found at least one answer to. I was working in a shop wherein the Architect insisted on having many fields of our entities read-only, i.e. without setters of any sort. I mean we were using Hibernate and obviously you can annotate the fields as read only...but his requirement was to eliminate the setters so they couldn't ever be set without using Reflection. He even wrote a suite of utilities that used Reflection to set those fields for testing and you had to extend them if there were changes to your schema. My problem with this was that it was dog slow and a big bunch of seemingly unnecessary code that was always changing. Mocks could be used of course but those can get painful as well if your data is non-trivial. Now I just found something that looks like a good answer but I would like to hear from the community as it may not be the best answer. For one thing, I question if we should have even been doing that.
You have several ways:
mocks - the simplest, e.g. Mockito library;
builders - setters only + validation on build;
package-local setters + same-package factories in tests scope.
Do NOT use:
100500 constructor arguments - this way leads to extremely hard-to-support code.
Builders example:
interface Model (
A getA();
...
)
public final class ModelBuilder {
private ModelBuilder() {...}
public static ModelBuilder newBuilder() {...}
public ModelBuilder setA(A a) (...) // keep 'a', return 'this'
...
public Model build() {...}
}