jeudi 12 mai 2022

Get children method's annotation in Java using reflection or something like this

OBS: My code is java 8.
For example, I have this stacktrace:

MainClass:MethodA() calls
--------ClassB:MethodB() calls
------------ClassC:MethodC() @Cacheable calls
----------------ClassFinal:MethodD()

MethodA() -> MethodB() -> MethodC() -> MethodD();


In my example, ClassC:methodC() it's noted with @Cacheable. I need get this annotation in ClassFinal:MethodD(), something like this:

    public void MethodD() {
        Cacheable cacheable = ...
    }

I already done this using reflection, but it isn't work with overload:

    public static <T extends Annotation> T getStacktraceAnnotation(Class<T> type) {
        int currStack = 0;
        T result = null;
        
        //
        //
        StackTraceElement[] stackTraceElementArray = Thread.currentThread().getStackTrace();
        
        //
        //
        for (java.lang.StackTraceElement curr : stackTraceElementArray) {
            try {
                Method[] methods = Class.forName(curr.getClassName()).getMethods();
                
                for (Method currMethod : methods) 
                    if (currMethod.getName().equals(curr.getMethodName())) {
                        result = currMethod.getAnnotation(type);
                        if (result != null) break;
                    }
                //
                //
                if (result != null || currStack++ > 6) break;
            } catch(Exception exc) {
                // Nothing!
            }
        }
        //
        //
        return result;
    }

Real stacktace of my program:

fff.commons.serverless.abstracts.v2.AbstractCommonIntegrationHttp.sendGet(AbstractCommonIntegrationHttp.java:320) 
fff.commons.serverless.abstracts.v2.Teste.a(Teste.java:14) 
fff.commons.serverless.abstracts.v2.Teste.main(Teste.java:18)

Teste.a(Teste.java:14) is noted with @Cachable
And I need get this anottation in sendGet(AbstractCommonIntegrationHttp.java:320)

My annotation:

@Retention(RUNTIME)
@Target({ TYPE, METHOD })
@Inherited
public @interface Cacheable {
    int secs() default 15;
}




Aucun commentaire:

Enregistrer un commentaire