Java 注解解析 + 案例演示

本文通过案例演示了如何使用Java反射API获取类、方法上的注解对象,读取注解属性值,并判断方法是否包含特定注解。示例中定义了一个自定义注解`MyAnnotation`,然后在`Test`类及其`show1`、`show2`方法上应用了此注解。通过`getAnnotation`和`isAnnotationPresent`方法,展示了获取和判断注解的完整过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注解解析:

        package java.lang.reflect.AnnotatedElement接口
                它有很多实现类:CLass、Method、Field、Constructor等都实现了该接口
                    - <T extends Annotation> T getAnnotation(Class<T> annotationClass)
                得到指定类型的注解引用,没有返回null
                   - default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
                判断指定的注解有没有

案例演示:

        需求:获取Test类上的注解对象

// 自定义注解

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String[] names();
    int age();
}
// Test类

@MyAnnotation(names = {"张三"},age = 18)
public class Test {
    public static void main (String[] args) throws NoSuchMethodException {
        // 需求:获取Test类上的注解对象,并且获得该注解的属性值

        // 1.获取Tests类的Class对象
        Class<Test> testClass = Test.class;

        // 2.获取该Class对象上的注解对象
        MyAnnotation annotation = testClass.getAnnotation(MyAnnotation.class);

        // 根据注解对象获取该注解的属性值
        String[] names = annotation.names();
        System.out.println(Arrays.toString(names));

        int age = annotation.age();
        System.out.println(age);

        System.out.println("======================================");

        // 需求2:获取show1方法上的注解对象,并且获取该注解的属性值
        // 1.获取show1方法的Mthod对象
        Method show1 = testClass.getDeclaredMethod("show1");
        // 2.获取该方法上的注解
        MyAnnotation annotation1 = show1.getAnnotation(MyAnnotation.class);
        // 3.根据注解获取属性上的值
        System.out.println(Arrays.toString(annotation1.names()));
        System.out.println(annotation1.age());

        System.out.println("======================================");

        // 需求3:判断Tetsts类中的方法是否包含MyAnnotatio注解
        // 1.获取show2方法的Method对象
        Method show2 = testClass.getDeclaredMethod("show2");
        // 2.判断show2方法是否包含MyAnnotation注解
        System.out.println(show2.isAnnotationPresent(MyAnnotation.class));
        System.out.println(show1.isAnnotationPresent(MyAnnotation.class));

        MyAnnotation annotation2 = show2.getAnnotation(MyAnnotation.class);
        System.out.println(annotation2);// null
    }

    @MyAnnotation(names = {"李四"},age = 18)
    public void show1(){
    }
    public void show2(){
    }
}

        输出结果:
            [张三]
            18
            ======================================
            [李四]
            18
            ======================================
            false
            true
            null

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值