Java Reflection Annotation getAnnotationFromStackTrace(Class annotationClass)

Here you can find the source of getAnnotationFromStackTrace(Class annotationClass)

Description

Returns first occurrence of specified annotation if one is found on method or class within current thread stack trace.

License

Apache License

Parameter

Parameter Description
annotationClass to search for

Return

found annotationClass or null if not found

Declaration

public static <T extends Annotation> T getAnnotationFromStackTrace(Class<T> annotationClass) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class Main {
    /**//from ww  w.ja  v  a  2 s.  c o m
     * Returns first occurrence of specified annotation if one is
     * found on method or class within current thread stack trace.
     * @param annotationClass to search for
     * @return found annotationClass or null if not found
     */
    public static <T extends Annotation> T getAnnotationFromStackTrace(Class<T> annotationClass) {
        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        for (StackTraceElement stack : trace) {
            Method method = null;
            Class<?> clazz = null;
            try {
                String methodName = stack.getMethodName();
                clazz = Class.forName(stack.getClassName());
                method = clazz.getMethod(methodName, null);
            } catch (Exception e) {
                //ignore
            }
            T annotation = null;
            if (method != null) {
                annotation = method.getAnnotation(annotationClass);
            }
            if (annotation != null) {
                return annotation;
            }
            annotation = clazz != null ? clazz.getAnnotation(annotationClass) : null;
            if (annotation != null) {
                return annotation;
            }
        }
        return null;
    }
}

Related

  1. getAnnotationFromAnnotation(Annotation annotation, Class annotationClass)
  2. getAnnotationFromEntityFields(Class entity, Class annotation)
  3. getAnnotationFromEntityOrInterface( Class annotationType, Class entity)
  4. getAnnotationFromField(Object object, Class annotationClass)
  5. getAnnotationFromJoinpointMethod(ProceedingJoinPoint joinpoint, Class annotationClass)
  6. getAnnotationFromWeldBean(Object target, Class annotation)
  7. getAnnotationFullname(Annotation annotation)
  8. getAnnotationInClass( final Class annotationClass, final Class clazz)
  9. getAnnotationInHeirarchy(Class annotationClass, Class aClass)