package cn.itcast.Reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ReflectDemo { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Class clazz = User.class; Object obj=create(clazz); System.out.println(obj); invoke1(obj,"showMessage"); System.out.println("-------------------------"); field(clazz); } //创建对象 static Object create(Class clazz) throws Exception{ Constructor con = clazz.getConstructor(String.class); Object obj = con.newInstance("test name"); return obj; } //调用方法 static void invoke1(Object obj,String methodName) throws Exception{ Method[] ms = obj.getClass().getMethods(); for(Method m:ms){ System.out.println(m.getName()); if(methodName.equals(m.getName())){ m.invoke(obj, null); } } Method m = obj.getClass().getMethod(methodName, null); m.invoke(obj, null); } static void field(Class clazz) throws Exception{ Field[] fs = clazz.getDeclaredFields(); //不会便利出私有变量 // fs = clazz.getFields(); for(Field f : fs){ System.out.println(f.getName()); } } }