免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2735 | 回复: 0
打印 上一主题 下一主题

Java反射(关于数组) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-06-25 14:54 |只看该作者 |倒序浏览
已知条件:
类型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());
    }
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/55983/showart_1977149.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP