java反射经典例子

package com.chen.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**经典反射例子
 * 
 * @author : EX-CHENWEIXIAN001 
 * @create_date :2013-2-26 下午04:53:55
 *
 */
public class Admin
{
    public Admin()
    {
    }

    private String id = "";

    public String getId()
    {
        System.out.print(id);
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException
    {
        String str = "com.chen.Test.Admin";
        Class c = Class.forName(str);
        Object obj = c.newInstance(); 
        // 这里是里设置属性的值
        Method m = c.getMethod("setId", new Class[]{ 
                Class.forName("java.lang.String") 
                });
        m.invoke(obj, new Object[]{ 
                "EX-CHENWEIXIAN001" 
                });
        // 这里是里获取属性的值
        m = c.getMethod("getId", new Class[] {});
        m.invoke(obj, new Object[] {});
    }
} 

 

posted on 2013-02-26 16:59  陈惟鲜的博客  阅读(181)  评论(0编辑  收藏  举报

导航