package fanshe; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class testDemo { public static void main(String[] args) throws Exception { method_9(); } private static void method_9() throws Exception, Exception { // TODO Auto-generated method stub Class clazz=Class.forName("fanshe.person"); Method method=clazz.getMethod("show",String.class); Object obj=clazz.newInstance(); method.invoke(obj,"show传值"); } private static void method_8() throws Exception { Class clazz=Class.forName("fanshe.person"); Method method=clazz.getMethod("show", null); //Object obj=clazz.newInstance(); Constructor constructor=clazz.getConstructor(String.class,int.class); Object obj=constructor.newInstance("李亮亮",33); method.invoke(obj,null); } //调用指定方法 private static void method_7() throws Exception { Class clazz=Class.forName("fanshe.person"); Method method=clazz.getMethod("show", null); Object obj=clazz.newInstance(); method.invoke(obj, null); } //获取指定Class中的公共函数 private static void method_6() throws Exception { Class clazz=Class.forName("fanshe.person"); Method[] methods=clazz.getMethods();//获取的共有方法 methods=clazz.getDeclaredMethods();//只获得本类中的所有方法 for(Method method:methods) { System.out.println(method); } } //设置字段 private static void method_5() throws Exception { Class clazz=Class.forName("fanshe.person"); Field field=clazz.getDeclaredField("age"); field.setAccessible(true); Object obj=clazz.newInstance(); field.set(obj, 33); Object o=field.get(obj); System.out.println(o); } //指定参数 private static void method_4() throws Exception { String clazz="fanshe.person"; Class c1=Class.forName(clazz); Constructor con=c1.getConstructor(String.class,int.class); person obj=(person) con.newInstance("小强",33); System.out.println(obj); } //反射创建对象 private static void method_3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { String clazz="fanshe.person"; Class c1=Class.forName(clazz); c1.newInstance(); /* Constructor con=c1.getConstructor(); person obj=(person) con.newInstance(); System.out.println(obj);*/ } private static void method_2() { Class<person> c1=person.class; Class<person> c2=person.class; System.out.println(c1==c2); } public static void method_1() { person p=new person(); Class c1=p.getClass(); person p1=new person(); Class c2=p1.getClass(); System.out.println(c1==c2); } }