集册 Java实例教程 如果给定类型具有带有给定注释的方法,则返回true

如果给定类型具有带有给定注释的方法,则返回true

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

454
如果给定类型具有带有给定注释的方法,则返回true
/** 来 自 时 代 J a v a - nowjava.com**/

//package com.nowjava;

import java.lang.annotation.Annotation;

import java.lang.reflect.AnnotatedElement;


import java.lang.reflect.Method;


public class Main {

    /**

     * Returns true if the given type has a method with the given annotation

     */

    public static boolean hasMethodWithAnnotation(Class<?> type,

            Class<? extends Annotation> annotationType,

            boolean checkMetaAnnotations) {

        try {

            do {

                Method[] methods = type.getDeclaredMethods();
                /** from 
                时 代 J a v a 公 众 号**/

                for (Method method : methods) {

                    if (hasAnnotation(method, annotationType,

                            checkMetaAnnotations)) {

                        return true;

                    }

                }

                type = type.getSuperclass();

            } while (type != null);

        } catch (Throwable e) {

            // ignore a class loading issue

        }

        return false;

    }


    /**

     * Checks if a Class or Method are annotated with the given annotation

     *

     * @param elem                 the Class or Method to reflect on

     * @param annotationType       the annotation type

     * @param checkMetaAnnotations check for meta annotations

     * @return true if annotations is present

     */

    public static boolean hasAnnotation(AnnotatedElement elem,

            Class<? extends Annotation> annotationType,

            boolean checkMetaAnnotations) {

        if (elem.isAnnotationPresent(annotationType)) {

            return true;

        }

        if (checkMetaAnnotations) {

            for (Annotation a :
展开阅读全文