如何为第三方类创建 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
}
现在我想创建一个 @Builder
以便我获得一个流畅的构建器 API 来简化具有默认值的 ThirdPartyPojo
的实例化。
这是我尝试过的:
@Builder
public class ThirdPartyPojoBuilder extends ThirdPartyPojo {
@Default
private String name = "default name";
// many more default values for other properties
}
代码可以编译,我可以引用生成器,例如
ThirdPartyPojo pojoWithDefaultName = ThirdPartyPojoBuilder.builder().build();
ThirdPartyPojo pojoWithCustomName = ThirdPartyPojoBuilder.builder().name("custom name").build();
System.out.println(pojoWithDefaultName.getName());
System.out.println(pojoWithCustomName.getName());
但是,这不起作用,因为 getName()
为 pojoWithDefaultName
和 pojoWithCustomName
返回 null
。
最佳答案
基于 pirho's answer ,我找到了一个可行的解决方案,它也支持默认值。
- 扩展第三方类
- 在类级别添加
@Builder
注解 - 添加应由构建器配置的任何字段
- 添加
@Default
并为任何应具有默认值的字段赋值 - 添加一个所有参数匹配所有字段的构造函数
- 为每个构造函数参数添加
this.set*(...)
例如
@Builder
public class ThirdPartyPojoBuilder extends ThirdPartyPojo {
@Default
private String name = "default name"
public ThirdPartyPojoBuilder(String name) {
this.setName(name);
}
}
它也支持默认值:
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"
关于java - 如何为第三方 POJO 创建构建器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70350039/