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 // declare a new annotation @Retention(RetentionPolicy.RUNTIME) @interface Demointerface { String str(); int val(); } public class ClassgetDeclaredAnnotationsExample2 { // set values for the annotation @Demointerface(str = "Demo Annotation", val = 100) // a method to call in the main public static void sample() { ClassgetDeclaredAnnotationsExample2 obj = new ClassgetDeclaredAnnotationsExample2(); try { Class cls = obj.getClass(); Method mthd = cls.getMethod("sample"); Annotation[] ann = mthd.getDeclaredAnnotations(); // print the annotation for (int i = 0; i < ann.length; i++) { //loop from I to length System.out.println(ann[i]); //print statement } } catch (NoSuchMethodException exc) { exc.printStackTrace(); // pritnt the stack trace for object } } public static void main(String args[]) { sample(); } }
Output