【发布时间】:2020-01-20 09:53:25
【问题描述】:
我一直在使用 SpringBatch 并查看该类的源代码
org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor<T>
我发现了这个:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = Arrays.asList(names).toArray(new String[names.length]);
}
- 把数组转成列表再转成数组的目的是什么?
- 为什么不使用这样的东西:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = names; // Simpler and without conversions
}
- 或者这样创建一个独立的新实例:
public void setNames(String[] names) {
Assert.notNull(names, "Names must be non-null");
this.names = names.clone(); //Simpler and create a new instance
}
欢迎所有答案。
【问题讨论】:
-
我想不出不使用克隆的具体原因,但有充分的理由复制名称。
-
这只是创建数组副本的一种效率不高的方法。
.clone()会做同样的事情,但可能会以更高效的方式。此外,在toArray()调用中提供非空数组现在被视为bad practice。您可以在github.com/spring-projects/spring-batch/issues 提交问题 -
所以代码想要有一个独立的副本,不能从外部更改。也许程序员不记得
clone或Arrays.copyOf。 -
查找“防御性复制”,就是这种技术的名称。
标签: java performance optimization spring-batch code-cleanup