我正在尝试使用相同的代码遍历许多自定义类的ArrayList,并认为使用反射会更容易。但是,当我尝试获取每个字段的引用时遇到了一个问题。这是我尝试运行的代码的一小部分。 (我的代码不同,但要点在其中):
import java.lang.reflect.*;
import java.util.ArrayList;
public class Stack {
public ArrayList<Custom1> cust11;
public ArrayList<Custom1> cust12;
public ArrayList<Custom1> cust13;
public ArrayList<Custom2> cust21;
public ArrayList<Custom2> cust22;
public ArrayList<Custom2> cust23;
public static void main(String args[]) {
Stack stack = new Stack();
}
public Stack() {
cust11 = new ArrayList<Custom1>();
cust12 = new ArrayList<Custom1>();
cust13 = new ArrayList<Custom1>();
cust21 = new ArrayList<Custom2>();
cust22 = new ArrayList<Custom2>();
cust23 = new ArrayList<Custom2>();
doReflect();
}
public void doReflect(){
Field[] fields = this.getClass().getFields();
for(Field f : fields) {
if(f.getName().contains("cust1")) {
try {
ArrayList<Custom1> temp = (ArrayList<Custom1>)f.get(cust11);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
class Custom1{
public Custom1() {}
}
class Custom2{
public Custom2() {}
}
到达
ArrayList<Custom1> temp = (ArrayList<Custom1>)f.get(cust11);
我明白了
java.lang.IllegalArgumentException: Can not set java.util.ArrayList field
Stack.cust11 to java.util.ArrayList
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(Unknown Source)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(Unknown Source)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at Stack.doReflect(Stack.java:33)
at Stack.<init>(Stack.java:25)
at Stack.main(Stack.java:14)
我该怎么做?
答案 0 :(得分:0)
我应该用过
ArrayList<Custom1> temp = (ArrayList<Custom1>)f.get(this);