一:java反射机制:
Java程序可以加载一个运行时才得知名称的class,获悉其完整构造(但不包括methods定义),并生成其对象实体、或对其fields设值、或唤起其methods.
java反射机制使用的包为:java.lang.refect;
二:反射机制相关类:
Class
Field
Method
PropertyDescriptor(Javabean相关类)
Constructor
三:相关方法
(1)Class相关方法
方法 | 描述 |
getCanonicalName() | 获取class的类名 |
getModifiers() | 获取class的修饰符 |
getTypeParameters() | 获取class的泛型参数 |
getGenericInterfaces() | 获取class实现的接口 |
getSuperclass() | 获取class的父类,多次调用即可获得继承的路径 |
getAnnotations() | 获取class的注解 |
Class API | 继承的?? | 私有的?? |
no | yes | |
yes | no | |
no | yes | |
yes | no |
Class API | 继承的方法? | 私有方法? |
no | yes | |
yes | no | |
no | yes | |
yes | no |
newInstance()
(2)获取Class对象
object.Class
Class.forName("")
(3)得到Class 的相关方法
PropertyDescriptor pd = new PropertyDescriptor(fieldname, ownerClass); Method method = pd.getWriteMethod();//获得写方法 Method method = pd.getReadMethod();//获得写方法
以及使用上面的方法
(4)Method的执行
调用Method 的invoke 方法
invoke(owner)
method.invoke(owner, args);(在此可以使用返回对象得到类型,为数据赋值)
四:PropertyDescriptor 属于javabean相关类
1、getPropertyType(),获得属性的Class对象。
2、getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法。
3、hashCode(),获取对象的哈希值。
4、setReadMethod(Method readMethod),设置用于读取属性值的方法;setWriteMethod(MethodwriteMethod),设置用于写入属性值的方法;
五:java为什么可以实现反射(具体看java的编译过程)
Java代码编译成字节码文件的过程中,JDK编译生成的字节码文件中含有相当多的关于类中各种信息的说明。
一个字节码文件 可以划分为五部份,第一部份是General Information也就是刚才看到的第一行,第二部分是常量池,第三部份是接口,第四部份是属性,第五部份是方法,
第一行还说明了类中常量池的数,方法数,属性数,访问标记等,第二行表示的就是类名,第三行就是父类名,父类名前的几个应该是常量池的索引号。