这段代码怎么移除@build和@data注解
时间: 2024-05-15 17:12:49 浏览: 62
@build和@data注解通常是Lombok库中使用的注解,用于自动生成Java类的构造函数、getter和setter等方法。如果要移除这些注解,需要手动编写这些方法。
例如,对于一个使用了@data注解的Java类,可以手动编写以下代码来实现相同的效果:
```java
public class MyClass {
private String name;
private int age;
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "MyClass{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
对于@build注解,可以手动编写以下代码来实现相同的效果:
```java
public class MyClass {
private String name;
private int age;
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
public static class Builder {
private String name;
private int age;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public MyClass build() {
return new MyClass(name, age);
}
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "MyClass{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
使用时,可以通过Builder类来创建对象:
```java
MyClass myObject = new MyClass.Builder()
.name("John")
.age(30)
.build();
```
阅读全文