java反射

 

public class TestPerson {

    private String name;
    
    private Integer sex;

    public String getName() {
        return "zhangsan";
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }
}

 

public class Test {

    public static void main(String[] args) throws SQLException,
            PropertyVetoException, InstantiationException,
            IllegalAccessException {
        try {
            // Class clazz =
            // Class.forName("ZZY.src.cn.qtone.oa.test.TestPerson");
            TestPerson clazz = (TestPerson) Class.forName(
                    "cn.qtone.oa.test.TestPerson").newInstance();
            System.out.println(clazz.getName());
            ;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

public class Test {

    public static void main(String[] args) throws SQLException,
            PropertyVetoException, InstantiationException,
            IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {
        try {
            Class clazz = Class.forName("cn.qtone.oa.test.TestPerson");
            TestPerson testPerson = new TestPerson();
            Method[] methods = clazz.getMethods();
            for (Method m : methods) {
                if (m.toString().indexOf("getName") > -1) {
                    System.out.println(m.invoke(testPerson));
                    ;
                }
                // System.out.println(m);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

posted @ 2017-02-06 10:34  N神3  阅读(143)  评论(0编辑  收藏  举报