Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...