Reputation: 6080
How to add using @Singular
attribute in lombok
Foo foo = ..;
FooActivity fa = ..;
foo.fooActivity(fa); // this fails - compilation error
@Builder
class Foo {
@Singular("fooActivity")
private List<FooActivity> fooActivities;
}
Upvotes: 2
Views: 2374
Reputation: 4935
@Singular
is to be used along with @Builder
annotation. So in this case the fooActivity
method to add an element to the list is created in the FooBuilder
class generated by lombok and it is NOT part of Foo
. Hence you cannot access fooActivity
using the Foo
object.
How to solve? (There is an issue with this approach, which I have mentioned in the end.)
You can solve this by having toBuilder
set to true
for the @Builder
annotation. This would generate a method in Foo
that would return a builder object, which you can use to invoke fooActivity
.
@Builder(toBuilder = true)
public class Foo {
@Singular("fooActivity")
private List<FooActivity> acts;
}
// To invoke
foo = foo.toBuilder().fooActivity(fa).build();
The issue with the above approach
toBuilder()
would generate a builder using the values in foo
and the build
would generate a NEW object. So you need to be careful with this because the original object foo
is not the one being updated using this approach.
Second Approach (Not recommended)
Use experimental feature @Delegate
. This is what the lombok website says about this feature:
Currently we feel this feature will not move out of experimental status anytime soon, and support for this feature may be dropped if future versions of javac or ecj make it difficult to continue to maintain the feature.
It would also cause issues when there are multiple collections in your class.
@Builder
public class Foo {
@Delegate
@Builder.Default
private List<FooActivity> acts = new ArrayList<>(); // make sure you do this while using @Delegate
}
To invoke
foo.add(fa);
Upvotes: 1
Reputation:
Have you tried something like this?
Foo myFoo = Foo.builder()
.fooActivity(new FooActivity())
.fooActivity(new FooActivity())
.build();
Upvotes: 2