您的位置:首页 > 编程语言 > Java开发

Java反射 1

2015-09-09 12:07 447 查看
public class TestMain {

    public static void main(String[] args) throws ClassNotFoundException, IllegalArgumentException,
            IllegalAccessException, SecurityException, NoSuchFieldException {

        AccessTest test = new AccessTest();
        test.setAge(22);
        test.setName("Kity");

        AccessTest test1 = new AccessTest();
        test1.setAge(26);
        test1.setName("Dong");

        Class<?> cls = Class.forName(AccessTest.class.getName());

        for (Field field : cls.getDeclaredFields()) {
            field.setAccessible(true); // 此处要声明,不然取不到会抛出异常
            System.out.println(field.get(test));
        }

        Field field = cls.getDeclaredField("name");
        field.setAccessible(true); // 此处要声明,不然取不到会抛出异常</span>
        System.out.println(field.get(test1));

        field.set(test1, "John");
        System.out.println(field.get(test1));

    }

}

class AccessTest {

    private int age;
    private String name;

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

}


输出:
22
Kity
Dong
John
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: