文章内容
1、什么是反射机制
反射就是把Java类中的各个成分映射成一个个的Java对象。即在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能调用它的任意一个方法和属性。这种动态获取信息及动态调用对象方法的功能叫Java的反射机制。
2、如何获得一个类的字节码文件
1)使用类的全路径
1 | Class<?> clazz = Class.forName( "com.ntan520.reflect.Person" ); |
2)类型.class
1 | Class clazz = Person. class ; |
3)对象.getClass()
1 2 | Person person = new Person(); Class clazz = person.getClass(); |
3、获得类的所有属性
1 2 3 4 5 6 | Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { String fieldName = field.getName(); System.out.println( "fieldName:" + fieldName); } |
4、获取类的所有方法
1 2 3 4 5 6 | Method[] declaredMethods = clazz.getDeclaredMethods(); for (Method method : declaredMethods) { String methodName = method.getName(); System.out.println( "methodName:" + methodName); } |
5、通过反射调用方法
1 2 3 4 5 6 7 | //调用setAge()getAge()方法 Method setAge = clazz.getDeclaredMethod( "setAge" , Integer. class ); Object instance = clazz.newInstance(); setAge.invoke(instance, new Integer( 1 )); Method getAge = clazz.getDeclaredMethod( "getAge" ); System.out.println(getAge.invoke(instance)); |