Online Java Compiler By
JavaTpoint.com
//import statements import java.lang.annotation.Retention; //import retention import java.lang.annotation.RetentionPolicy; //import retention policy import java.lang.reflect.Method; import java.lang.annotation.Annotation; //import annotation // create custom annotation having two values @Retention(RetentionPolicy.RUNTIME) @interface SelfCreatedAnnotationinterface { public String key(); //method public String value(); } // Another class on which we want to apply an annotation class DemoClass { private String field; @SelfCreatedAnnotationinterface(key = "getFieldvalue", value = "getting field attribute") public String getFieldvalue() { return field; } } public class ClassgetDeclaredAnnotationsExample1 { public static void main(String[] args) { Method[] mthd = DemoClass.class.getMethods(); Annotation[] ann = mthd[0].getDeclaredAnnotations(); for (Annotation an : ann) { SelfCreatedAnnotationinterface selfann = (SelfCreatedAnnotationinterface)an; System.out.println("key: " + selfann.key()); System.out.println("value: " + selfann.value()); } } }
Output