我有一个内班和一个外班。使用Java Reflection我想访问内部类实例的数据。
public class OuterClass {
public OuterClass() {
super();
}
public OuterClass(InnerClass innerClass1, InnerClass innerClass2) {
super();
this.innerClass1 = innerClass1;
this.innerClass2 = innerClass2;
}
private InnerClass innerClass1;
private InnerClass innerClass2;
public class InnerClass {
public InnerClass() {
super();
}
public InnerClass(int id, String name, String rollNo) {
super();
this.id = id;
this.name = name;
this.rollNo = rollNo;
}
private int id;
private String name;
private String rollNo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
public InnerClass getInnerClass1() {
return innerClass1;
}
public void setInnerClass1(InnerClass innerClass1) {
this.innerClass1 = innerClass1;
}
public InnerClass getInnerClass2() {
return innerClass2;
}
public void setInnerClass2(InnerClass innerClass2) {
this.innerClass2 = innerClass2;
}
}
主要类别: -
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Reflection {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
OuterClass outerClass = new OuterClass();
OuterClass.InnerClass innerClass1 = outerClass.new InnerClass(1, "Iftekhar", "1234");
OuterClass.InnerClass innerClass2 = outerClass.new InnerClass(2, "Ahmed", "123");
outerClass.setInnerClass1(innerClass1);
outerClass.setInnerClass2(innerClass2);
Field[] fields = outerClass.getClass().getDeclaredFields();
for (Field f : fields) {
Method method = OuterClass.InnerClass.class.getMethod("getId", null);
int id = (int) method.invoke(f, null);
System.out.println(id);
}
}
}
我预计输出为1和2.但我得到以下例外: -
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
我使用上面的方式实例化内部类属性。任何人都可以帮助我做错了。
答案 0 :(得分:3)
您正在getId()
个实例上调用java.lang.reflect.Field
。 java.lang.reflect.Field
不是OuterClass.InnerClass
的实例。
要解决此问题,首先必须获取该字段的值并在其上调用getId()
:
Field[] fields = outerClass.getClass().getDeclaredFields();
// We only have to find the method once and can reuse it
Method method = OuterClass.InnerClass.class.getMethod("getId");
// We have to call .setAccessible because the fields are private
AccessibleObject.setAccessible(fields, true);
for (Field f : fields) {
OuterClass.InnerClass value = (OuterClass.InnerClass) f.get(outerClass);
// At this point, you could also use value.getId();
int id = (int) method.invoke(value);
System.out.println(id);
}