java再复习——通过反射读取注解

来源:互联网 发布:淘宝网店充话费 编辑:程序博客网 时间:2024/06/05 14:41

通过反射读取类的注解与属性的注解的相关常用API

public class AnnoationTest {public static void main(String[] args) throws ClassNotFoundException {//通过反射加载类Class<Student> clazzClass = (Class<Student>) Class.forName("Student");//读取类的注解(getAnnotations()方法读取到的注解时包括父类的,考虑到继承关系的,所以不介意使用)Annotation[] annotations = clazzClass.getDeclaredAnnotations();for(int i=0;i<annotations.length;i++){System.out.println(annotations[i]);Table table = (Table) annotations[i];System.out.println(table.name());}//或者System.out.println("-----------------");if(clazzClass.isAnnotationPresent(Table.class)){//判断有没有指定注解(此方法对Class,Field等都可以使用)Table annotation = clazzClass.getAnnotation(Table.class);System.out.println(annotation);}System.out.println("-----------------通过反射读取类的属性");//获取这个类所有声明的属性,不能使用getFields方法,这个方法只是获取到public访问域的属性Field[] declaredFields = clazzClass.getDeclaredFields();for (int i=0;i<declaredFields.length;i++) {Field field = declaredFields[i];System.out.println(field);//获取这个属性上声明的注解Annotation[] annotations2 = field.getDeclaredAnnotations();for (Annotation annotation : annotations2) {System.out.println(annotation);}System.out.println("----------获取到想要的注解,以及相应的注解值");if(field.isAnnotationPresent(Column.class)){Column annotation = field.getAnnotation(Column.class);System.out.println(annotation.name() + "--" + annotation.isId());}}}}


0 0