我正在尝试自动化定制程序的测试过程,这些程序旨在解决竞争性编程挑战。下面是解决方案的虚拟示例实现:
public class Solution {
private static String dummyField = "initial";
public static int initialize(InputStream in) {
//competitive programmer custom code
System.out.println(dummyField);
dummyField = "changed";
return subCaseCount;
}
public void processSingleSubCase(InputStream in) {
//competitive programmer custom code
}
}
为解决方案预先编写的测试代码,无论其实现如何:
public void testSolution() throws FileNotFoundException {
for(File testResource : testResources) {
InputStream in = new FileInputStream(testResource);
int subCaseCount = Foo.initialize(in);
for (int subCase = 0; subCase < subCaseCount; subCase++) {
new Foo().processSingleSubCase(in);
}
//magic call to re-init all static fields without knowing their number/names in advance goes here
}
//console current output:
//initial
//changed
//changed
//...
//desired:
//initial
//initial
//initial
//....
}
静态字段可以是可变的,因此缓存初始值并使用反射将它们映射到字段名称作为第一个设置,然后在迭代之间重新分配它们是行不通的。
我确实想出了一个可行的解决方案,它基本上在迭代之间使用不同的类加载器重新加载类,它确实有效,但速度很慢:仅重新加载类就需要大约50秒 300 次(测试资源是自动生成的,我希望能够灵活地自动生成尽可能多的次数)。
有更快的替代方案吗?
最佳答案
我对如何做到这一点的两个想法是:
使用实例而不是
静态
,因为这样每个测试的新实例都是新鲜的。如果您需要(或想要)坚持使用
static
:在第一次测试之前,缓存static
值,然后从缓存中重新分配它们测试之间。如果静态
值是引用可变对象的对象引用,则需要进行深层复制。
关于java - 是否可以重新初始化类中的静态可变字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43235742/