Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of fields with annotation, by using reflection

I create my annotation

public @interface MyAnnotation { } 

I put it on fields in my test object

public class TestObject {      @MyAnnotation      final private Outlook outlook;     @MyAnnotation      final private Temperature temperature;      ... } 

Now I want to get list of all fields with MyAnnotation.

for(Field field  : TestObject.class.getDeclaredFields()) {     if (field.isAnnotationPresent(MyAnnotation.class))         {               //do action         } } 

But seems like my block do action is never executed, and fields has no annotation as the following code returns 0.

TestObject.class.getDeclaredField("outlook").getAnnotations().length; 

Is anyone can help me and tell me what i'm doing wrong?

like image 206
user902383 Avatar asked May 16 '13 10:05

user902383


People also ask

How do you inherit fields using Reflection?

The only way we have to get only inherited fields is to use the getDeclaredFields() method, as we just did, and filter its results using the Field::getModifiers method. This one returns an int representing the modifiers of the current field. Each possible modifier is assigned a power of two between 2^0 and 2^7.

What is a reflection annotation?

Annotations are a kind of comment or meta data you can insert in your Java code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection. Here is an example of class annotation: @MyAnnotation(name="someName", value = "Hello World") public class TheClass { }

How do you inherit annotations?

Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it. The annotation can be overridden in case the child class has the annotation.


2 Answers

You need to mark the annotation as being available at runtime. Add the following to your annotation code.

@Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { } 
like image 124
Zutty Avatar answered Oct 20 '22 01:10

Zutty


/**  * @return null safe set  */ public static Set<Field> findFields(Class<?> classs, Class<? extends Annotation> ann) {     Set<Field> set = new HashSet<>();     Class<?> c = classs;     while (c != null) {         for (Field field : c.getDeclaredFields()) {             if (field.isAnnotationPresent(ann)) {                 set.add(field);             }         }         c = c.getSuperclass();     }     return set; } 
like image 40
Mindaugas K. Avatar answered Oct 19 '22 23:10

Mindaugas K.