Search code examples
javainterfaceannotationsfinal

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


Solution

  • 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());
                    }
                }
            }
        }
    }