I'm using Lombok for POJOs generation:
@Value
@AllArgsConstructor
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
@Builder(toBuilder = true, builderClassName = "builder")
public class Student{
String name;
String age;
}
My question is: How can I change the value of the fields for a generated POJO?
CodePudding user response:
@Value creates the immutable object. you can't change the value of field once object initialised. You can create new object by changing specific property by using toBuilder method. e.g:
Student s1 = Student.builder()
.name("Sam")
.age("11")
.build();
Student s2 =s1.toBuilder()
.age("12")
.build();
Or you need to remove @Value annotation and add @Data. Then you can use setter for the property.
CodePudding user response:
you can use this annotation in the above your pojo class @Builder(toBuilder = true)
Student student1 = Student.builder()
.name("foo")
.id(1)
.build();
Student.StudentBuilder studentBuilder = testStudent.toBuilder();
also you can use just @Data annotation instead of @NoArgConstructor, @AllArgConstructor, because @Data annotation completed them.
if you have a problem,which @Data annotation, generally this problem occur when using relationship entity, if so than you can use @ToString.Exclude annotation in the relationship entity.
CodePudding user response:
Student Student = Student.builder()
.name("Sam")
.age("11")
.build();
CodePudding user response:
You have to add @Getter and @Setter just before Steudent. Then you can change the value of a field automatically by setName(value).
Example:
Steudent s = new Student();
s.setName("toto");
