0

I'm using Lombok for POJOs generation, so how can I change the value of the fields?

@Value
@AllArgsConstructor
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
@Builder(toBuilder = true, builderClassName = "builder")
public class Student{
  String name;
  String age;
}
Andre
  • 70
  • 5
Razvan
  • 347
  • 1
  • 11

4 Answers4

3

@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.

2

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 = student1.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.

1

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");
Mureinik
  • 297,002
  • 52
  • 306
  • 350
-1
Student Student = Student.builder()
                .name("Sam")
                .age("11")
                .build();
Maheen N
  • 31
  • 5