dimanche 22 septembre 2019

How to get annotations of a caller method from another class

I am using jdk1.8.0_221 and I want to load specific configuration inside the constructor of super class based on calling two different types of methods. I am seeking for the best practice and preferably a convenient approach.

package test;
public class A extends Z{
    @Marker1
    public void f1() {
        Z.g();
    }
    @Marker2
    public void f2() {
        Z.g();
    }
}

package test;
public class B extends Z{
    @Marker1
    public void f3() {
        Z.g();
    }
    @Marker2
    public void f4() {
        Z.g();
    }
}

package core;
public class Z{
    public Z() {
        //I want to determine here that which type of method (Marker1 or Marker2) calls constructor
    }
    public static void g(){
        //some code goes here
    }
}

Note1: There are many methods from different classes that calls Z.g(), so I could not use the explicit name of class to get methods and its annotations.

Note2: All of configurations should be done inside the constructor of super class of Z.

Note3: The g() method is not necessarily static.

I have tried the following snippet but getMethodName() return always <init>:

public Z() Throws NoSuchMethodException, ClassNotFoundException{
    StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
    StackTraceElement ste = stElements[3];// or stElements[2]
    Class<?> aClass = Class.forName(ste.getClassName());
    String methodName = ste.getMethodName();
    Method method = aClass.getMethod(methodName);
    Annotation[] annotations = aClass.getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation.getClass().equals(Marker1.class)) {
             //load conf1
             break;
         } else if (annotation.getClass().equals(Marker2.class)) {
             //load conf2
             break;
         }
     }
}

Also, I have tried many solutions in stackoverflow and other communities which not worked properly.





Aucun commentaire:

Enregistrer un commentaire