栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Annotation自定义注解使用,并通过类反射获取到该注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Annotation自定义注解使用,并通过类反射获取到该注解

1、定义一个注解

示例:

@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    String value() default  "";
    String msg() default "";

}

@Target-标记这个注解在什么地方使用
其中有10个枚举值,有两个是jdk1.8后新增的,暂时不知道用法

package java.lang.annotation;

public enum ElementType {
    TYPE,               

    FIELD,              

    METHOD,             

    PARAMETER,          

    CONSTRUCTOR,        

    LOCAL_VARIABLE,     

    ANNOTATION_TYPE,    

    PACKAGE             
    
    TYPE_PARAMETER     

    TYPE_USE           
}

@Retention-标记这个注解在什么时间使用
其中有3个枚举值

package java.lang.annotation;
public enum RetentionPolicy {
    SOURCE,            

    CLASS,             

    RUNTIME            
}

2、通过类的反射获取到注解以及注解的值

demo示例:

package com.zy.demo;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@TestAnnotation(msg = "类上的注解msg")
public class Test {

    @TestAnnotation("value")
    private String msgClass;

    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        //获取类上的注解
        TestAnnotation annotation = Test.class.getAnnotation(TestAnnotation.class);
        if (annotation != null) {
            System.out.println("value的值为" + annotation.value());
            System.out.println("msg的值为" + annotation.msg());
        }
        //获取方法上的注解
        Method method = Test.class.getMethod("testMsg");
        TestAnnotation annotation1 = method.getAnnotation(TestAnnotation.class);
        if (annotation1 != null) {
            System.out.println("-----------------");
            System.out.println("value的值为" + annotation1.value());
            System.out.println("msg的值为" + annotation1.msg());
        }
        //获取属性上的注解
        Field a = Test.class.getDeclaredField("msgClass");
        TestAnnotation annotation2 = a.getAnnotation(TestAnnotation.class);
        if (annotation1 != null) {
            System.out.println("-----------------");
            System.out.println("value的值为" + annotation2.value());
            System.out.println("msg的值为" + annotation2.msg());
        }
    }

    @TestAnnotation(value = "方法上的注解value" ,msg = "方法上的注解msg")
    public void testMsg() {
    }
}


执行结果为:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/327628.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号