将 AutoValue 与 Builder 模式一起使用时,如何在构造函数中初始化其他自定义最终字段?
例子
@AutoValue
abstract class PathExample {
static Builder builder() {
return new AutoValue_PathExample.Builder();
}
abstract String directory();
abstract String fileName();
abstract String fileExt();
Path fullPath() {
return Paths.get(directory(), fileName(), fileExt());
}
@AutoValue.Builder
interface Builder {
abstract Builder directory(String s);
abstract Builder fileName(String s);
abstract Builder fileExt(String s);
abstract PathExample build();
}
}
在现实世界的类中,初始化(如在 `fullPath 字段中)更昂贵,所以我只想做一次。我看到了两种方法:
1) 延迟初始化
private Path fullPath;
Path getFullPath() {
if (fullPath == null) {
fullPath = Paths.get(directory(), fileName(), fileExt());
}
return fullPath;
}
2)在构建器中初始化
private Path fullPath;
Path getFullPath() {
return fullPath;
}
@AutoValue.Builder
abstract static class Builder {
abstract PathExample autoBuild();
PathExample build() {
PathExample result = autoBuild();
result.fullPath = Paths.get(result.directory(), result.fileName(), result.fileExt());
return result;
}
是否有另一种选择,以便该fullPath
领域可以是最终的?