|
| 1 | +package com.ddb.javacore.annotation; |
| 2 | + |
| 3 | +import java.lang.reflect.Field; |
| 4 | + |
| 5 | +public class AnnotationProcessor { |
| 6 | + |
| 7 | + @SuppressWarnings("deprecation") |
| 8 | + public static void main(String[] args) throws Exception { |
| 9 | + // 得到Class实例 |
| 10 | + Class<?> clazz = Person.class; |
| 11 | + |
| 12 | + // 得到被反射类的一个实例 |
| 13 | + Person person = (Person) clazz.newInstance(); |
| 14 | + System.out.println("Person 默认值:"); |
| 15 | + person.showInfo(); |
| 16 | + |
| 17 | + // 获得所有的字段 |
| 18 | + Field[] fields = clazz.getDeclaredFields(); // 不能获取到继承的属性 |
| 19 | + // Field[] fields = clazz.getFields(); //可以获取到公开的继承的属性 |
| 20 | + /* |
| 21 | + Field[] fields3 =new Field[fields.length+fields2.length]; |
| 22 | + System.arraycopy(fields, 0, fields3, 0, fields.length); |
| 23 | + System.arraycopy(fields2, 0, fields3,fields.length, fields2.length); |
| 24 | + 如果是需要获取抽象类中的属性,则需要通过获得一个新的数组,将所有的属性值放置在同一个数组中,然后继续遍历 |
| 25 | + */ |
| 26 | + for (Field field : fields) { |
| 27 | + // 判断该属性上是否存在HelloWorld注解 |
| 28 | + if (field.isAnnotationPresent(HelloWorld.class)) { |
| 29 | + // 获取指定的注解 |
| 30 | + HelloWorld annotation = field.getAnnotation(HelloWorld.class); |
| 31 | + System.out.println("HelloWorld注解的值是:" + annotation.value()); |
| 32 | + |
| 33 | + // 打破封装 |
| 34 | + field.setAccessible(true); |
| 35 | + // 将注解的值赋给属性值 |
| 36 | + field.set(person, annotation.value()); |
| 37 | + |
| 38 | + } /*else if (field.isAnnotationPresent(Default.class)) { |
| 39 | + Default default1 = field.getAnnotation(Default.class); |
| 40 | + System.out.println("Default注解的值是:" + default1.value()); |
| 41 | + field.setAccessible(true); // 获取字段的数据类型 |
| 42 | + System.out.println(field.getType().getSimpleName().toString()); |
| 43 | +
|
| 44 | + switch (field.getType().getSimpleName().toString()) { |
| 45 | + case "int": |
| 46 | + field.set(person, Integer.valueOf(default1.value())); |
| 47 | + break; |
| 48 | + case "double": |
| 49 | + field.set(person, Double.valueOf(default1.value())); |
| 50 | + break; |
| 51 | + case "String": |
| 52 | + field.set(person, default1.value()); |
| 53 | + break; |
| 54 | + default: |
| 55 | + break; |
| 56 | + } |
| 57 | + }*/ |
| 58 | + } |
| 59 | + |
| 60 | + System.out.println("注解后的值:"); |
| 61 | + person.showInfo(); |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments