已知条件:
类型A,A中有数组类型的字段
结果:
将A中的数组类型字段实例化
public class A {
private B[] bs;
public A() {
}
/** * @return the bs */ public B[] getBs() { return bs; }
/** * @param bs the bs to set */ public void setBs(B[] bs) { this.bs = bs; } }
|
public class B {
private String s;
public B() {
}
public B(String s) { this.s = s; }
/** * @return the s */ public String getS() { return s; }
/** * @param s the s to set */ public void setS(String s) { this.s = s; } }
|
即:将A中的bs实例化,但bs这个名字不是预先知道的
public class TestRef {
/** * @param args */ public static void main(String[] args) throws Exception {
A a = new A();
Field field = a.getClass().getDeclaredField("bs");
System.out.println(field.getType());
Class cls = field.getType();
Class c1 = cls.getComponentType();
// B b = (B) cls.newInstance();
String name = c1.getName(); // System.out.println(name);
Class c = Class.forName(name); Object o = c.newInstance();
Object b = Array.newInstance(c1, 2);
Array.set(b, 0, c.newInstance()); Array.set(b, 1, c.newInstance());
//
// c.newInstance();
Method method = a.getClass().getDeclaredMethod("setBs", cls);
// B[] bs = new B[2];
// bs[0] = new B("1111");
// bs[1] = new B("22222222");
method.invoke(a, b);
System.out.println(a.getBs()[0].getS()); System.out.println(a.getBs()[1].getS()); }
}
|
阅读(1735) | 评论(0) | 转发(0) |