Java Reflection Annotation getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass)

Here you can find the source of getAnnotation(final AnnotatedElement annotatedElement, final Class annotationClass)

Description

Returns the annotation or null if the element is not annotated with that type.

License

Apache License

Declaration

public static <A extends Annotation> A getAnnotation(final AnnotatedElement annotatedElement,
        final Class<A> annotationClass) 

Method Source Code


//package com.java2s;
/*/*from   www  .j a v a2s  . c  o m*/
 * Copyright (C) 2015 Sebastian Daschner, sebastian-daschner.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/LICENSE2.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.AnnotatedElement;

import java.util.*;

import java.util.stream.Stream;

public class Main {
    /**
     * Returns the annotation or {@code null} if the element is not annotated with that type.
     * <b>Note:</b> This step is necessary due to issues with external class loaders (e.g. Maven).
     * The classes may not be identical and are therefore compared by FQ class name.
     */
    public static <A extends Annotation> A getAnnotation(final AnnotatedElement annotatedElement,
            final Class<A> annotationClass) {
        final Optional<Annotation> annotation = Stream.of(annotatedElement.getAnnotations())
                .filter(a -> a.annotationType().getName().equals(annotationClass.getName())).findAny();
        return (A) annotation.orElse(null);
    }
}

Related

  1. getAnnotation(Class clazz, Method method, int parameterIndex)
  2. getAnnotation(Class cls, Annotation... annotations)
  3. getAnnotation(Class cls, Method... methods)
  4. getAnnotation(Class lookingFor, Annotation[] annotations)
  5. getAnnotation(Enum enumConstant, Class annotationClass)
  6. getAnnotation(final Class c, final Class annClass)
  7. getAnnotation(final Class annotatedClass, final Class annotationClass)
  8. getAnnotation(final Class type, final Class annotation)
  9. getAnnotation(final Class reference, final AccessibleObject obj)