我想使用反射来设置私有字段的值以进行单元测试.
问题是,该字段是静态的.
这是我正在做的工作:
/**
* Use to set the value of a field you don't have access to, using reflection, for unit testing.
*
* Returns true/false for success/failure.
*
* @param p_instance an object to set a private field on
* @param p_fieldName the name of the field to set
* @param p_fieldValue the value to set the field to
* @return true/false for success/failure
*/
public static boolean setPrivateField(final Object p_instance, final String p_fieldName, final Object p_fieldValue) { …Run Code Online (Sandbox Code Playgroud) 我有一个Java类,有很多Fields.
我想循环al alhe字段并为那些为null的那些做一些事情.
例如,如果我的班级是:
public class ClassWithStuff {
public int inty;
public stringy;
public Stuff;
//many more fields
}
Run Code Online (Sandbox Code Playgroud)
In another location, I'd make a ClassWithStuff object and I would like to go though all the fields in the class. Kind of like this:
for (int i = 0; i < ClassWithStuff.getFields().size(); i++) {
//do stuff with each one
}
Run Code Online (Sandbox Code Playgroud)
Is there any way for me to achieve this?
我有一个静态类(Foo)和一个主类(Main)
请参阅Main.java:
public class Main {
public static void main(String[] args) {
System.out.println(Foo.i); // 0
Foo.i++;
System.out.println(Foo.i); // 1
// restart Foo here
System.out.println(Foo.i); // 1 again...I need 0
}
}
Run Code Online (Sandbox Code Playgroud)
见Foo.java:
public class Foo {
public static int i = 0;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法重启或重置静态类?
注意:我需要这个,因为我正在使用jUnit测试静态类,我需要在第二次测试之前清理参数.
编辑
几乎解决方案:
使用StanMax答案,我可以这样:
Main.java
public class Main {
public static void main(String[] args) throws Exception {
test();
test();
}
public static void test() throws Exception {
System.out.println("\ntest()");
MyClassLoader myClassLoader = new MyClassLoader();
Class<?> fooClass = …Run Code Online (Sandbox Code Playgroud)