简体   繁体   中英

How to create Java field annotations for final variables in my Interface

Can I create annotations for the final variables in my interface and access the same?

For Example I have the below Annotation & Interface:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
     String   description();      
}

public interface MyInterface
{
    @MyAnnotation(description="This is a Final variable in MyInterface")
    public static final String MY_FINAL_VAR = "MyFinalVariable";
}

How will I convert my final variable String to Field? Say

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class MyAnnotationRunner{
        public static void main(String[] args){
             Field field = ????????????????????????????????
             MyAnnotation myAnnotation = (MyAnnotation)field.getAnnotation(MyAnnotation.class);
             if(myAnnotation != null ){
                 System.out.println("Description: " + myAnnotation.description());
             }
        }
}

Thanks

you get it like this

public class MyAnnotationRunner {
    public static void main(String[] args) {
        Field[] fields = MyInterface.class.getFields();
        for(Field field:fields){
            for(Annotation ann:field.getAnnotations()){
                if (ann instanceof MyAnnotation){
                    MyAnnotation my = (MyAnnotation)ann;
                    System.out.println(my.description());
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM