注解简单理解

1 篇文章 0 订阅

 

注解在spring框架中经常使用。

java从1.5开始支持注解。

注解的理解:

注解是什么?

从JDK5开始,Java增加对元数据的支持,也就是注解,注解与注释是有一定区别的,可以把注解理解为代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,并执行相应的处理。通过注解开发人员可以在不改变原有代码和逻辑的情况下在源代码中嵌入补充信息。

注解怎么用?

@XXXXX

定义类,方法时,加上@XXX

@MyFirstAnnotation(value = "test")
    public  void test() throws NoSuchMethodException {
        //方法上面的注解获取
        MyFirstAnnotation annotation = this.getClass().getMethod("test").getAnnotation(MyFirstAnnotation.class);
//        注解对象的使用
        System.out.println("method="+annotation.method());
        System.out.println("value="+annotation.value());
    }

自己怎么写一个注解?

/**
 * 自定义一个注解
 * @Documented  定义该注解是否出现在javadoc中,可选
 * @Target(ElementType.TYPE)  指定Annotation的类型属性,指定其修饰的是类,接口,或者方法,可选,不指定,则所有地方都能使用
 * @Retention(RetentionPolicy.RUNTIME) 指定annotation的策略属性,可选运行时或者类加载
 * @interface  定义注解,意味实现了Annotation接口
 *
 */

底层实现是动态代理。

package com.wang.annotation;


import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

public class AnnotationTest {


    public static void main(String[] args) throws NoSuchMethodException {
        AnnotationTest annotationTest = new AnnotationTest();
        annotationTest.test();
    }

    /**
     * 注解的使用
     * test方法具有注解MyFirstAnnotation
     * @throws NoSuchMethodException
     */

    @MyFirstAnnotation(value = "test")
    public  void test() throws NoSuchMethodException {
        //方法上面的注解获取
        MyFirstAnnotation annotation = this.getClass().getMethod("test").getAnnotation(MyFirstAnnotation.class);
//        注解对象的使用
        System.out.println("method="+annotation.method());
        System.out.println("value="+annotation.value());
    }
}

/**
 * 自定义一个注解
 * @Documented  定义该注解是否出现在javadoc中,可选
 * @Target(ElementType.TYPE)  指定Annotation的类型属性,指定其修饰的是类,接口,或者方法,可选,不指定,则所有地方都能使用
 * @Retention(RetentionPolicy.RUNTIME) 指定annotation的策略属性,可选
 * @interface  定义注解,意味实现了Annotation接口
 *
 */

@Documented
//@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyFirstAnnotation {
    String value() default "";
    String method() default "POST";
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值