Java Reflection Annotation getAnnotation(Class clazz, Class annotationType)

Here you can find the source of getAnnotation(Class clazz, Class annotationType)

Description

Retrieve an annotation from a possibly proxied CDI/Weld class.

License

Apache License

Parameter

Parameter Description
clazz class to search annotation.
annotationType type of annotation to search for.
T annotation subclass.

Return

annotation instance or null if none found.

Declaration

public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationType) 

Method Source Code


//package com.java2s;
/*//from  www  .ja va  2  s  .c  om
 * Copyright ? 2017 Ivar Grimstad (ivar.grimstad@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    /**
     * Retrieve an annotation from a possibly proxied CDI/Weld class. First inspect
     * the class and if that fails, try using an annotated type obtained from CDI's
     * bean manager.
     *
     * @param clazz          class to search annotation.
     * @param annotationType type of annotation to search for.
     * @param <T> annotation subclass.
     * @return annotation instance or {@code null} if none found.
     */
    public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationType) {
        T an = clazz.getDeclaredAnnotation(annotationType);
        if (an == null && isProxy(clazz)) {
            an = clazz.getSuperclass().getDeclaredAnnotation(annotationType);
        }
        return an;
    }

    /**
     * Search for a method annotation following the inheritance rules defined by the
     * JAX-RS specification, and also stated in the MVC specification. If an annotation is
     * not defined on a method, check super methods along the class hierarchy first. If
     * not found, then look at the interface hierarchy. Note that this method implements
     * a depth-first search strategy.
     *
     * @param method method to start search at.
     * @param annotationType annotation class to search for.
     * @param <T> annotation subclass.
     * @return annotation instances or {@code null} if not found.
     */
    public static <T extends Annotation> T getAnnotation(Method method, Class<T> annotationType) {
        // If we reached Object.class, we couldn't find it
        final Class<?> clazz = method.getDeclaringClass();
        if (clazz == Object.class) {
            return null;
        }

        // Check if annotation declared (but not inherited) on method
        T an = method.getDeclaredAnnotation(annotationType);
        if (an != null) {
            return an;
        }

        // Other MVC annotations on this method, then inheritance disabled
        if (hasMvcOrJaxrsAnnotations(method)) {
            return null;
        } else {
            // Search for overridden method in super class
            final Class<?> superClass = method.getDeclaringClass().getSuperclass();
            if (superClass != null) {
                try {
                    final Method superMethod = superClass.getDeclaredMethod(method.getName(),
                            method.getParameterTypes());
                    an = getAnnotation(superMethod, annotationType);
                } catch (NoSuchMethodException e) { // NOPMD ignore empty catch block
                    // falls through
                }
                if (an != null) {
                    return an;
                }
            }

            // Now search for overridden method in super interfaces
            final Class<?>[] interfaces = method.getDeclaringClass().getInterfaces();
            for (Class<?> in : interfaces) {
                try {
                    final Method superMethod = in.getDeclaredMethod(method.getName(), method.getParameterTypes());
                    an = getAnnotation(superMethod, annotationType);
                } catch (NoSuchMethodException e) { // NOPMD ignore empty catch block
                    // falls through
                }
                if (an != null) {
                    return an;
                }
            }

            // Not found, return null
            return null;
        }
    }

    /**
     * Checks if the supplied type is a proxy. This method works with both
     * Weld and OpenWebBeans.
     *
     * @param clazz Type to check
     * @return whether the class is a proxy or not
     */
    private static boolean isProxy(Class<?> clazz) {
        Class<?> parent = clazz.getSuperclass();
        if (parent != null) {
            return clazz.getName().contains("$$") && clazz.getName().startsWith(parent.getName());
        }
        return false;
    }

    /**
     * Determines if a method has one or more MVC or JAX-RS annotations on it.
     *
     * @param method method to check for MVC or JAX-RS annotations.
     * @return outcome of test.
     */
    static boolean hasMvcOrJaxrsAnnotations(Method method) {
        return Arrays.stream(method.getDeclaredAnnotations()).anyMatch(a -> {
            final String an = a.annotationType().getName();
            return an.startsWith("javax.mvc.") || an.startsWith("javax.ws.rs.");
        });
    }
}

Related

  1. getAnnotation(Class clazz, Class annotation)
  2. getAnnotation(Class clazz, Class annotationClass)
  3. getAnnotation(Class clazz, Class annotationClass)
  4. getAnnotation(Class clazz, Class annotationClass)
  5. getAnnotation(Class clazz, Class annotationType)
  6. getAnnotation(Class clazz, Class annotationType)
  7. getAnnotation(Class clazz, String fieldName, Class annotationClass)
  8. getAnnotation(Class clazz, String name, Class[] types, Class annotationType)
  9. getAnnotation(Class cls, Class annotationClass)