@Value and @Data are both annotations provided by Lombok that can help reduce boilerplate code in Java applications.
@Value is used to create immutable objects with final fields, getter methods, and a constructor that accepts all fields as arguments. This annotation automatically generates the following code for a class:
- A private final field for each non-static field in the class
- A public getter method for each field
- A constructor that accepts all fields as arguments
- An equals method that compares all fields for equality
- A hashCode method that uses all fields to generate a hash code
- A toString method that includes the class name and all field values
Original Code:
import lombok.Value;
@Value
public class Person {
String name;
int age;
}
Generated Code:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
public final class Person {
private final String name;
private final int age;
public Person(final String name, final int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public boolean equals(final Object o) {
if (o == this) {
return true;
} else if (!(o instanceof Person)) {
return false;
} else {
Person other = (Person)o;
if (this.getAge() != other.getAge()) {
return false;
} else {
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name != null) {
return false;
}
} else if (!this$name.equals(other$name)) {
return false;
}
return true;
}
}
}
public int hashCode() {
int PRIME = true;
int result = 1;
int result = result * 59 + this.getAge();
Object $name = this.getName();
result = result * 59 + ($name == null ? 43 : $name.hashCode());
return result;
}
public String toString() {
return "Person(name=" + this.getName() + ", age=" + this.getAge() + ")";
}}
No comments:
Post a Comment