validate Annotation Element Type - Java java.lang.annotation

Java examples for java.lang.annotation:Annotation Type

Description

validate Annotation Element Type

Demo Code

/*/*from   w w  w .ja v a2 s . co  m*/
 * Copyright (c) 2008 Kasper Nielsen.
 *
 * 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 static java.util.Objects.requireNonNull;

import java.lang.annotation.ElementType;

import java.lang.annotation.Target;

public class Main {
    public static <T> Class<T> validateAnnotationElementType(
            Class<T> annotationType, ElementType elementType) {
        requireNonNull(annotationType, "annotationType is null");
        requireNonNull(elementType, "elementType is null");
        Target t = annotationType.getAnnotation(Target.class);
        if (t == null) {
            return annotationType;
        }
        for (ElementType et : t.value()) {
            if (et == elementType) {
                return annotationType;
            }
        }
        throw new IllegalArgumentException("Specified annotation type @"
                + annotationType.getSimpleName() + " must have "
                + elementType.toString().toLowerCase()
                + " target type (@Target(ElementType." + elementType + ")");
    }
}

Related Tutorials