package reflect;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList; import org.junit.Test;/* *java 反射技术学习 */public class Demo2 { @Test public void test1() { // TODO Auto-generated method stub try { // 1、加载类的字节码,方式 1 Class clazz = Class.forName("reflect.Person"); // 2、加载类的字节码,方式 2 clazz = new Person().getClass(); // 3、加载类的字节码,方式 3 clazz = Person.class; // 得到Person 类的所有方法 Method[] personMethods = clazz.getDeclaredMethods(); System.out.println("Person 的所有函数:"); for(Method m : personMethods){ System.out.print(m.getName()+" "); } System.out.println(new ArrayList()); // 得到 Person 类的构造函数 Constructor[] cons = clazz.getConstructors(); // 得到 Person 类的属性域 Field[] field = clazz.getFields(); Person p = new Person("zeng yao",22); // 调用无参的构造函数实例化Person对象 //p = (Person) clazz.newInstance(); //调用Person 的showInfo()方法 //p.showInfo(); //通过反射调用showInfo方法 Method method = clazz.getMethod("showInfo"); method.invoke(p); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}