反射:
其实就是动态的从内存加载一个指定的类,并获取该类中的所有的内容。
反射的好处:大大的增强了程序的扩展性。
反射的基本步骤:
1 |
Class clazz = Class.forName("com.makaruina.reflect.Person"); |
创建对象的两种方式(其实就是对象在进行实例化时的初始化方式):
1 2 3 |
Class clazz = Class.forName("com.makaruina.reflect.Person"); Constructor con = clazz.getConstructor(new Class[]{String.class,int.class}); Person instance = (Person) con.newInstance("name",20); |
综上所述,第二种方式,必须要先明确具体的构造函数的参数类型,不便于扩展。所以一般情况下,被反射的类,内部通常都会提供一个公有的空参数的构造函数。
1、获取方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// 获取类中所有的方法。 public static void method_1() throws Exception { Class clazz = Class.forName("com.makaruina.reflect.Person"); // 获取的是该类中所有的公有方法,包含继承和实现的方法。 Method[] methods = clazz.getMethods(); // 获取的是该类中的所有方法,包含私有方法,但不包含继承的方法。 methods = clazz.getDeclaredMethods(); for (Method method : methods) { System.out.println(method); } } // 获取指定方法; public static void method_2() throws Exception { Class clazz = Class.forName("com.makaruina.reflect.Person"); // 获取指定名称的方法。 Method method = clazz.getMethod("show", int.class, String.class); // 想要运行指定方法,当然是方法对象最清楚,为了让方法运行,调用方法对象的invoke方法即可,但是方法运行必须要明确所属的对象和具体的实际参数。 Object obj = clazz.newInstance(); method.invoke(obj, 39, "hehehe");// 执行一个方法 } // 想要运行私有方法。 public static void method_3() throws Exception { Class clazz = Class.forName("com.makaruina.reflect.Person"); // 想要获取私有方法。必须用getDeclearMethod(); Method method = clazz.getDeclaredMethod("method", null); // 私有方法不能直接访问,因为权限不够。非要访问,可以通过暴力的方式。 method.setAccessible(true);// 一般很少用,因为私有就是隐藏起来,所以尽量不要访问。 } // 反射静态方法。 public static void method_4() throws Exception { Class clazz = Class.forName("com.makaruina.reflect.Person"); Method method = clazz.getMethod("function", null); method.invoke(null, null); } |
2、获取属性
1 2 3 4 5 6 7 8 |
Field getField(String name) //返回一个 Field 对象,它反映此 Class 对象所表示的类或接口的指定公共成员字段。 Field[] getFields() //返回一个包含某些 Field 对象的数组,这些对象反映此 Class 对象所表示的类或接口的所有可访问公共字段。 Field getDeclaredField(String name) //返回一个 Field 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明字段。 Field[] getDeclaredFields() //返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有字段。 |
3、获取构造函数
1 2 3 4 |
Constructor<T> getConstructor(Class<?>... parameterTypes) //返回一个 Constructor 对象,它反映此 Class对象所表示的类的指定公共构造方法。 Constructor<?>[] getConstructors() //返回一个包含某些 Constructor 对象的数组,这些对象反映此 Class 对象所表示的类的所有公共构造方法。 |
感谢分享
2016年12月20日 下午3:04互联网开源精神,互帮互助!!!
2016年12月29日 下午1:57