1.反射的定义
反射就是动态获取一个类对象的成员(属性和方法)信息。
2.获取类对象的三种方式
第一种:通过Class类的forName方法,参数是类的全限定类名
第二种:通过类名.class获取,class属性
第三种:类实例对象.getClass方法
3.与反射相关的类
Class
Field
获取方式:
getFields() getDeclaredFields() (两者区别是可以获取非public的属性)
getField(String name) getDeclaredField(String name)
获取到Field类对象之后,是用于对属性赋值
set(实例对象,值)
Method
获取方式:
getMethods() getDeclaredMethods()
getMethod(String name,类<?>...parameterTypes) getDeclaredMethod(String,类<?>...parameterType)
获取到Method类对象之后,是用于执行该方法
invoke(实例对象,参数值)
Constructor
获取方式:
getConstructors() getDeclareConstructors()
getConstructor(类<?>...parameterTypes) getDeclaredConstructors(类<?>...parameterTypes)
获取到Constructor类对象之后,是用于创建实例对象
newInstance()
4.通过反射获取注解信息
获取方式:
getAnnotations() getAnnotation(类<A> annotationClass)
获取到annotationClass类对象之后,可以用于获取注解对应的参数,将其与数据库的相应字段相关联从而进行基本的操作。