I know if we know the annotation class, we can easily get the specific annotation and access its attribute. For example:
field.getAnnotation(Class<T> annotationClass)
Which will return a reference of specific annotation interface, so you can easily access its values.
My question is if I have no pre knowledge about the particular annotations class. I just want to use reflection to get all the annotation class name and their attributes at run-time for the purpose of dumping the class information for example as a JSON file. How can I do it in an easy way.
Annotation[] field.getAnnotations();
This method will only return dynamic proxies of the annotation interfaces.
Field[] fields = Test.class.getDeclaredFields(); for (Field field : fields) { if(field.isAnnotationPresent(FieldDescr.class)){ MyAnnotation myAnnotation = field.getAnnotation(MyAnnotation.class); System.out.println(myAnnoatation.name()); } }
In the above example name is the attribute of MyAnnotion which is an annotation interface.