如何为第三方类创建 Lombok 构建器(即我无法修改其源代码)?
我有一个无法更改的现有课程:
public class ThirdPartyPojo {
// one of many properties
private String name;
public ThirdPartyPojo() {
// default no-args constructor
}
String getName() {
return this.name;
}
void setName(String name) {
this.name = name;
}
// many more getters and setters
}
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个@Builder,以便获得流畅的构建器 API 来简化ThirdPartyPojo默认值的实例化。
这是我尝试过的:
@Builder
public class ThirdPartyPojoBuilder extends ThirdPartyPojo {
@Default
private String name = "default name";
// many more default values for other properties
}
Run Code Online (Sandbox Code Playgroud)
代码编译,我可以引用构建器,例如
ThirdPartyPojo pojoWithDefaultName = ThirdPartyPojoBuilder.builder().build();
ThirdPartyPojo pojoWithCustomName = ThirdPartyPojoBuilder.builder().name("custom name").build();
System.out.println(pojoWithDefaultName.getName());
System.out.println(pojoWithCustomName.getName());
Run Code Online (Sandbox Code Playgroud)
然而,这不能作为和的getName()回报。nullpojoWithDefaultNamepojoWithCustomName
根据pirho 的回答,我找到了一个可行的解决方案,该解决方案也遵循默认值。
@Builder在类级别添加注释@Default向应具有默认值的任何字段添加并分配值this.set*(...)为每个构造函数参数添加例如
@Builder
public class ThirdPartyPojoBuilder extends ThirdPartyPojo {
@Default
private String name = "default name"
public ThirdPartyPojoBuilder(String name) {
this.setName(name);
}
}
Run Code Online (Sandbox Code Playgroud)
它还支持默认值:
ThirdPartyPojo pojoWithDefaultName = ThirdPartyPojoBuilder.builder().build();
ThirdPartyPojo pojoWithCustomName = ThirdPartyPojoBuilder.builder().name("custom name").build();
System.out.println(pojoWithDefaultName.getName()); // prints "default name"
System.out.println(pojoWithCustomName.getName()); // prints "custom name"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1271 次 |
| 最近记录: |