isAnnotationPresent

isAnnotationPresent 是 java.lang.reflect.AnnotatedElement 接口定义的方法,用于判断元素是否直接声明指定运行时注解;需注解 Retention 为 RUNTIME,且 @Inherited 仅对类生效。Java 中可以通过 isAnnotationPresent 方法在反射中快速判断某个类、方法、字段等是否被特定注解标记,从而实现运行时的条件分支逻辑。

  isAnnotationPresent(Class extends Annotation> annotationClass) 是 java.lang.reflect.AnnotatedElement 接口定义的方法,所有可被注解的元素
(如 Class、Method、Field、Constructor 等)都继承了它。它返回 true 表示该元素上直接声明了指定注解(不包含继承自父类或接口的注解,除非该注解本身标注了 @Inherited)。

  基本用法示例

// 扫描
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) // 作用域类
public @interface ComponentScan {
String value();
}

    使用例子:


package com.ehs.user;

import com.ehs.springframework.ComponentScan;

@ComponentScan("com.ehs.user")
public class AppConfig {
}

 应用:

private Class configClazz;

// 用于判断类configClazz 上是否有ComponentScan 注解
 if (configClass.isAnnotationPresent(ComponentScan.class)) {

            ComponentScan annotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
           // 注解的值(com.ehs.user) 
String path = annotation.value();
}

 

posted @ 2026-11-15 12:50  东北大亨  阅读(6)  评论(0)    收藏  举报