提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
如果存在注释,则返回指定类型的注释,否则返回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();