1
我有一段代码,它看起来象下面这样:分裂了Java生成器来避免写相同的代码多次
Problem hashProblem;
String indexName;
if(condition.getOwner() != null) {
indexName = sourceLocation ;
hashProblem = new Problem().builder()
.locationID(condition.getLocationID())
.sourceLocation(condition.getSourceLocation())
.build();
}
else {
indexName = currentLocation;
hashProblem = new Problem().builder()
.locationID(condition.getLocationID())
.currentLocation(criteria.getcurrentLocation())
.build();
}
是否有更优雅的方式来写这个代码的方法吗?在构建hashProblem对象时,始终需要设置locationID。我无法想出一种方法来拆分构建器,以便我只能编写一次.locationID。我正在使用龙目岛(https://projectlombok.org/features/Builder.html)作为建造者
我忘了提及我正在使用龙目岛的建设者。如果我不使用新的Problem(),我会得到一个预期的错误方法调用 – user1692342
如果我使用Lombok的Builder:Builder b = new Problem()。builder()。locationID(condition.getLocationID()); ,我得到一个错误Incompatible types – user1692342
代替'Builder b',不管'Problem()。builder()'返回什么类型''''。我只是称它为'Builder',因为这是构建器类的通常名称。 –