publicstaticvoidmain(String[] args){ User user = new User(1, "Alice", "Passw0rd");
// [3]. 用反射读取 annotation 内容 if (user.getClass().isAnnotationPresent(ScopeMeta.class)) { System.out.println("Class User uses annotation ScopedMeta"); }
Field[] fields = user.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(ResponseMeta.class)) { ResponseMeta meta = field.getAnnotation(ResponseMeta.class); System.out.printf("Field '%s' - %s\n", field.getName(), meta); if (meta.editable()) { System.out.printf("Field '%s' is editable", field.getName()); } } } }
输出:
Class User uses annotation ScopedMeta Field ‘id’ - @annotation.ResponseMeta(country=CHINA, description=User’s identifier, editable=false) Field ‘username’ - @annotation.ResponseMeta(country=GERMANY, description=, editable=true) Field ‘username’ is editable