Checks if the direct parent (i.e., enclosing element) of this element is annotated with the given annotation type, and if so, returns the annotation object. - Java java.lang.annotation

Java examples for java.lang.annotation:Annotation Type

Description

Checks if the direct parent (i.e., enclosing element) of this element is annotated with the given annotation type, and if so, returns the annotation object.

Demo Code

/*/*from www .j  a  va2s.  co m*/
 * Copyright (c) 2014 by Malte Isberner (https://github.com/misberner).
 * 
 * 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.
 */
//package com.java2s;
import java.lang.annotation.Annotation;

import javax.lang.model.element.Element;

public class Main {
    /**
     * Checks if the direct parent (i.e., enclosing element) of this element is annotated
     * with the given annotation type, and if so, returns the annotation object.
     * <p>
     * This method is safe in the sense that it won't result in a {@link NullPointerException}
     * when the specified element does not have a parent, or a <tt>null</tt> element reference
     * is specified.
     * 
     * @param elem the element
     * @param annotationType the annotation type to check for
     * @return the annotation object, if the specified element has a parent that is annotated
     * with the given annotation type.
     */
    public static <A extends Annotation> A getParentAnnotation(
            Element elem, Class<A> annotationType) {
        if (elem == null) {
            return null;
        }
        Element enclosing = elem.getEnclosingElement();
        if (enclosing == null) {
            return null;
        }
        return enclosing.getAnnotation(annotationType);
    }
}

Related Tutorials