Javase——注解

注解:是一种特殊的注释,可以被编译器javac VM识别的注释

 

常见的三种注解类型

@Override 检查重写父类方法

@Deprecated 标识方法果实

@SupressWarnings({"警告类型1"}) 取消编译器经过

 

元注解 :约束注解的功能

共有四个:

@Retention() 指定注解使用生命周期

@Target() 指定注解使用的范围

@Documentted() 指定被修饰的注解将被javadoc工具提取成文档

@Inherited() 用于指定被@Inherited修饰的注解具有继承性

 

 

//指定注解使用的范围

@Target({ElementType.TYPE,ElementType.FIELD})

注意:当注解未指定Target值时,默认支持全部ElementType类型

 

ElementType 枚举类型

 

TYPE // 适用于class interface enum

FIELD // 适用 属性

METHOD // 适用 方法

PARAMETER//使用方法

CONSTRUCTOR//适用构造器

LOCAL_VARIABLE//适用于局部变量

ANNOTATION_TYPE//使用注解型态

PACKAGE//适用于包

 

//关于ElementType的源码

public enum ElementType {

/** Class, interface (including annotation type), or enum declaration */

TYPE,//修饰类

 

/** Field declaration (includes enum constants) */

FIELD,//修饰属性

 

/** Method declaration */

METHOD,//修饰方法

 

/** Formal parameter declaration */

PARAMETER,//修饰形参

 

/** Constructor declaration */

CONSTRUCTOR,//修饰构造器

 

/** Local variable declaration */

LOCAL_VARIABLE,//修饰局部变量

 

/** Annotation type declaration */

ANNOTATION_TYPE,//

 

/** Package declaration */

PACKAGE,//修饰包

 

/**

* Type parameter declaration

*

* @since 1.8

*/

TYPE_PARAMETER,//成员变量

 

/**

* Use of a type

*

* @since 1.8

*/

TYPE_USE

}

 

//指定注解使用的声明周期

@Retention(RetentionPolicy.RUNTIME)

默认是RetentionPolicy.CLASS

RetentionPolicy 枚举类型

//RetentionPolicy源码如下

public enum RetentionPolicy {

/**

* Annotations are to be discarded by the compiler.

*/

SOURCE,//不能加载到编译器中

 

/**

* Annotations are to be recorded in the class file by the compiler

* but need not be retained by the VM at run time. This is the default

* behavior.

*/

CLASS,//可以被加载到字节码文件中

 

/**

* Annotations are to be recorded in the class file by the compiler and

* retained by the VM at run time, so they may be read reflectively.

*

* @see java.lang.reflect.AnnotatedElement

*/

RUNTIME//可以加载到字节码文件中,也能被VM读取,也就是运行时,可以访问注解信息

}

 

 

自定义注解

 

自定义注解及使用如下:

@Target({ElementType.TYPE,ElementType.FIELD})

@Retention(RetentionPolicy.RUNTIME)

@interface MyAnnotation{

int num() default 10;

String value() default "aa";

}

 

@MyAnnotation

class Student{

@MyAnnotation

private int id;

}

public class AnnotationTest {

}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罗少说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值