反射

来源:互联网 发布:苏新诗毛糙体简 mac 编辑:程序博客网 时间:2024/06/14 20:38
public class Text {    /**     * @param args     * @throws ClassNotFoundException      * @throws SecurityException      * @throws NoSuchMethodException      */    public static void main(String[] args) throws  Exception {        // TODO Auto-generated method stub        /*         * 三种方式的反射:         *///      第一种//      Class<?> forName = Class.forName("com.libin.text.Person");        Person person = new Person();//      第二种//      Class<? extends Person> class1 = person.getClass();//      第三种        Class<Person> class2=Person.class;//      调用person的方法,第一个参数,是要查找的方法;第二个参数是该方法的参数类型//      当我把setname方法设置成私有的时候,就不可以使用了//      Method method = class2.getMethod("setName", String.class);//      获取私有方法        Method method = class2.getDeclaredMethod("setName", String.class);//      设置暴力反射        method.setAccessible(true);//      执行反射的方法        method.invoke(person, "李彬");        Method method2 = class2.getDeclaredMethod("getName", null);        method2.setAccessible(true);        String name=(String) method2.invoke(person, null);        System.out.println(name);    }}

Person

package com.libin.text;public class Person {    private String name;    private String sex;    private int age;    public Person(String name, String sex, int age) {        super();        this.name = name;        this.sex = sex;        this.age = age;    }    public Person() {        super();        // TODO Auto-generated constructor stub    }    private String getName() {        return name;    }    private void setName(String name) {        this.name = name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}
0 0