문제

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());
                }
            }
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top