java注解简单实现

感谢老铁https://blog.csdn.net/briblue/article/details/73824058

注解类

import java.lang.annotation.*;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;

//注解保留时间(保留到程序运行的时候,会加载到jvm)
@Retention(RetentionPolicy.RUNTIME)
//能够将注解中的元素包含到javadoc中
@Documented
//注解应用的地方(方法上,类上)
@Target({METHOD,TYPE,FIELD})
//被注解注解的类被继承,子类也被注解
//@Inherited
public @interface TestAnnotation {
    int id() default -1;
    String msg() default "hi";
}

注解简单实现类

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//@TestAnnotation(id = 1, msg ="hello" )
@TestAnnotation
public class Test {

    @TestAnnotation
    int a;

    @TestAnnotation
    public void say(){
        System.out.println("方法");
    }
    public static void main(String[] args) {
        //判断是否应用了某个注解
        boolean hasAnnotation=Test.class.isAnnotationPresent(TestAnnotation.class);
        System.out.println("应用了注解"+hasAnnotation);
        if(hasAnnotation){
            //获取指定类型的注解
            TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
            System.out.println("获取类注解值");
            System.out.println("---------id---------"+testAnnotation.id()+"\n"+"---------msg-------"+testAnnotation.msg());
        }

        //获取成员变量上注解
        try {
            Field field=Test.class.getDeclaredField("a");
            field.setAccessible(true);
            TestAnnotation testAnnotation2=field.getAnnotation(TestAnnotation.class);
            if(testAnnotation2 != null){
                //获取成员变量值
                System.out.println("获取成员变量值");
                System.out.println("---------id---------"+testAnnotation2.id()+"\n"+"---------msg-------"+testAnnotation2.msg());
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        //获取方法上注解
        try {
           Method m= Test.class.getDeclaredMethod("say");
            TestAnnotation t3=m.getAnnotation(TestAnnotation.class);
            if(null != t3){
                System.out.println("获取方法变量值");
                System.out.println("---------id---------"+t3.id()+"\n"+"---------msg-------"+t3.msg());
            }
            //获取注解名字
            Annotation[] t4=m.getAnnotations();
            System.out.println("获取方法变量值2");
            System.out.println("------------------"+t3.annotationType().getSimpleName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值