public class reflectionTest { public static void main(String[] args) throws Exception { Person person = new Person(); Class c = person.getClass(); //获取类的元数据对象
//使用反射机制,实例化对象 Constructor personconstroctor = c.getConstructor(String.class,int.class); //通过反射机制获取Person类中接收一个String参数和一个int参数的public构造方法的引用(获取构造方法) Person p = (Person) personconstroctor.newInstance("abc",25); //实例化成一个对象 System.out.println(p);
//使用反射机制,获取类里面的属性 Field[] personfields = c.getDeclaredFields(); for (Field f : personfields) { System.out.println(f); } //循环打印属性 Field nameField = c.getDeclaredField("name"); //从原型(类的元数据对象)里获取一个属性 nameField.setAccessible(true); //允许更改(无论是privated,还是protected) nameField.set(p,"ssss"); //更改对象的值 System.out.println(p); //使用反射机制,调用类里面的方法 Method[] personmethods = c.getDeclaredMethods(); // for (Method m : personmethods) { System.out.println(m); }