集册 Java实例教程 如果存在注释,则返回指定类型的注释,否则返回null。

如果存在注释,则返回指定类型的注释,否则返回null。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

388
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
如果存在注释,则返回指定类型的注释,否则返回null。


//package com.nowjava;

import java.lang.annotation.Annotation;

/** 
 来自 nowjava.com - 时  代  Java**/

public class Main {

    public static void main(String[] argv) throws Exception {

        Class clazz = String.class;

        Class annotationClass = String.class;

        System.out.println(getAnnotationInLineage(clazz, annotationClass));

    }


    /**

     * Returns an annotation for the specified type if such an annotation is present, else null. The superclasses of the

     * class are included in the search if the annotation is not found in the leaf class.

     * <p/>

     * This method find the same kinds of annotations that are found by {@link Class#getAnnotation(Class)} with the

     * exception that it includes superclasses in the search as well.

     *

     * @param <A>             the annotation

     * @param clazz           the class

     * @param annotationClass the class of the annotation you are looking for.

     * @return the annotation if present, otherwise null

     * @see Class#getAnnotation(Class) for more details

     */

    public static <A extends Annotation> A getAnnotationInLineage(

            Class<?> clazz, Class<A> annotationClass) {


        A annotation = clazz.getAnnotation(annotationClass);

        if (annotation != null) {

            return annotation;/*时 代 J a v a 公 众 号 提 供*/

        }


        Class<?> superClass = clazz.getSuperclass();
展开阅读全文