vendredi 9 février 2018

Getting annotation of functions using reflection [duplicate]

I cannot get annotation of this function myMethod

public class Meta {

    @MyAnno(str = "MyMethod Function", val = 2)
    @What(description = "Function to test Annotation based functions")
    void myMethod() {
        System.out.println("Hello from MyMethod");
    }
}

using this code

public class MainClass {

    public static void main(String[] args) {
        Meta2 ob = new Meta2();
        Class<?> cl = ob.getClass();

        try {
            Method m = cl.getMethod("myMethod");
            Annotation[] anArr = m.getDeclaredAnnotations();
            for (Annotation a : anArr) {
                System.out.println(a);
            }
        } catch (NoSuchMethodException ex) {
            System.out.println(ex);
        }
    }
}

The program throws NoSuchMethodException that there is no function myMethod in the class Meta2. When i changed the access modifier to public, i got the annotation But not with default access modifier, Why ?





Aucun commentaire:

Enregistrer un commentaire