文章目录
- 定义
- class
- Class
- 获取一个类的类对象
- 反射的具体步骤
- 1.加载类
- 2.实例化
- 3.获取
- 1)获取类中方法
- 2)获取构造方法
- 3)获取当前类的属性
- 4.方法调用
- 应用
定义
- 反射是操作其属性和方法从编码期决定转为在运行期决定
- 编码期决定:创建固定类的对象,调用这个对象的属性和方法
- 运行期决定:灵活创建想要创建的对象(参数中传入想要创建对象的字符串),再调用这个对象的属性和方法,这样做可以提高代码的灵活度,适度使用;过度使用会降低代码的运行效率,增加资源开销。
class
- 静态属性,class在Object中定义,所有的类都有这个静态属性。例:
String.class、int.class
Class
- 类,Class类的每个实例用于表示JVM加载的一个类
获取一个类的类对象
- 直接调用该类的静态属性class
Class cls=String.class;
- 调用Class的静态方法forName
Class cls=Class.formName("java.lang.String")
- 通过对象获取该类
Class cls=new User().getClass()
- 通过类加载器ClassLoader
InputStream=getClass()(或类名.class).getClassLoader().getResourceAsStream(fileName)
反射的具体步骤
1.加载类
Class cls=Class.forName("类的全称")
类API
String cls.getName()
String cls.getPackage().getName()
String cls.getSimpleName()
String cls.getSuperclass().getSimpleName()
Annotation[] cls.getAnnotations()
RequestMapping cls.getAnnotation(RequestMapping.class);
2.实例化
Object cls.newInstance()
3.获取
1)获取类中方法
Method[] cls.getMethods()
Method cls.getMethod(String name, Class<?>... parameterTypes)Method[] cls.getDeclaredMethods()
Method method=cls.getDeclaredMethod("方法名", null)
method.getName()
Params params = method.getAnnotation(Params.class)
Class[] method.getParameterTypes()
2)获取构造方法
Constructor co=cls.getConstructor(int.class)
Constructor[] con=cls.getConstructors()
3)获取当前类的属性
Field[] fields=cls.getFields()
Field field=cls.getField("a")Field[] fields = cls.getDeclaredFields()
Field field = cls.getDeclaredField("code")String field.getName()
String field.getType().getName()
Column column = field.getAnnotation(Column.class)
4.方法调用
- 属性
int a=field.getInt(Object obj)
- 调用
Object method.invoke(Object obj, Object... args)
- 无参方法的调用示例
Object obj=Test.class.newInstance()
method.invoke(obj)
- 有参方法的调用示例
Object obj=Test.class.newInstance()
Class[] types=method.getParameterTypes()
Object[] params=new Object[types.length]
for(int i=0;i<types.length;i++){if(types[i]==String.class){params[i]="hello"}if(types[i]==int.class) {params[i]=100}
}
Object method.invoke(obj,params)
应用
1.遍历对象属性,进行赋值
Class cls=obj.getClass();
Field[] fields = cls.getDeclaredFields();
for(Field field:fields){String fieldName=field.getName();if(fieldName.contains("serialVersionUID") || fieldName.contains("create") || fieldName.contains("update")){continue;}fieldName=(fieldName.substring(0,1).toUpperCase())+fieldName.substring(1);Method getMethod = cls.getMethod("get"+fieldName);String type = field.getGenericType().toString();if(type.equals("class java.lang.String")){String value = (String) getMethod.invoke(obj);if(value==null){continue;}if(value.equalsIgnoreCase("N/A")){Method setMethod = cls.getMethod("set"+fieldName,new Class[] {String.class});setMethod.invoke(obj,new Object[] {null});}}
}