反射
解释:反射是对编译成的class文件进行解析,拿到其属性和方法
1 2 3 4 5 6 7
| Class 新名 = 类名.class;
Class 新名 = Class.forName("包名.类名");
根据类new一个对象; Class 新名 = 对象.getClass();
|
- 拿到属性
- 通过field得到属性的类型和名字 得到方法 用method
1 2 3 4 5 6 7 8 9 10 11 12
| Field[] fields = 新名.getDeclaredFields();
for(Fiedl field : fields){ System.out.println(field.getName(); }
Field 新属性名 = 新名.getDeclaredFields("属性名");
新属性名.getType();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| Method[] methods = 新名.getDeclaredMethods();
Method[] methods = 新名.getMethods();
for(Method method : Methods){ String str = method.getName() + ":" + method.getReturnType().getTypeName(); Class<?>[] str2 = method.getParameterTypes(); for(Class<?> class1 : str2){ system.out.println(class1.getName()); } Method[] methods = 新名.getDeclaredMethods("方法名",参数列表每一个参数的类型的类); People p = (People) people.newInstance(); 方法名.invoke(p,赋的值); }
|
1 2 3 4 5 6 7 8
| ArrayList<String> str = new ArrayList<>(); ArrayList<Integer> inte = new ArrayList<>();
Class str1 = str.getClass(); Class inte1 = inte.getClass();
system.out.println(str1==inte1);
|
输出结果为true,验证正确,反射确实是去泛型
反射的实际应用
1 2 3 4 5 6 7 8 9
| @Documented @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface RealName {
String name() default "";
}
|
1 2 3 4
| @RealName(name = "我") private String me; @RealName(name = "我的实际名字") private String myRealName;
|
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
| Map<String,String> map = new HashMap<>(); try { Class<?> printClass = Class.forName("com.simplemw.user"); Field[] fields = printClass.getDeclaredFields(); for (Field field : fields) { String isNotNullStr = ""; boolean annotationPresent = field.isAnnotationPresent(RealName.class); if (annotationPresent) { RealName realName = field.getAnnotation(RealName.class); isNotNullStr = realName.name(); } map.put(field.getName(),isNotNullStr); } } catch (Exception e) { e.printStackTrace(); }
for (String str:map.keySet()) { System.out.println(str+"---"+map.get(str)); }
|