java.lang包 分析_java.lang.annotation包类的浅析

1、先看一下annotation包下的类,作者的jdk是1.6版本。

01359142e62134187d7f5211ca2c12e1.png

Annotation是接口,the common interface extended by all annotation types,意思就就是说Annotation是所有注解类型的父类型,个人感觉就像是注解’界‘的Object,Annotation有四个方法,但是自定义的注解是不可以重写Annotation这四个方法的。这与Object中的不同之处。

2、@interface Retention

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.ANNOTATION_TYPE)

public @interface Retention {

RetentionPolicy value();

}

Retention:“保留,拘留”的意思。在注解中用于标识注解被保留多久(由于注解的保留的属性不同,在jvm中驻留的时间也不同)如果在注解上没加@Retention注解,则默认的保留策略是ClASS。该注解作用范围就是在注解上,用于属性和方法是不起作用的。

3、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

}

SOURCE:注解将在编译的时候被忽略;

ClASS:编译之后注解将被保留在字节码文件中,但是在不会在vm运行时保留。默认策略;

RUNTIME:注解会保留在字节码文件中,同时在vm运行时始终存在,而且可以通过反射获取相对应的信息。

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.ANNOTATION_TYPE)

public @interface Target {

ElementType[] value();

}

Target是指示该注解适用的范围,如果Target元注解没有在注解上声明,该自定义的注解可以在程序的任何地方使用。如果在Target中出现超过一次的同样的ElementType的枚举值,就会报编译时错误。如果在Target({})这样使用,该注解就不能在外部使用了。

public enum ElementType {

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

TYPE,

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

FIELD,

/** Method declaration */

METHOD,

/** Parameter declaration */

PARAMETER,

/** Constructor declaration */

CONSTRUCTOR,

/** Local variable declaration */

LOCAL_VARIABLE,

/** Annotation type declaration */

ANNOTATION_TYPE,

/** Package declaration */

PACKAGE

}

使用范围:

TYPE:类、接口、注解、枚举类型;

FIELD:属性;

METHOD:方法;

PARAMETER:参数;

CONSTRUCTOR:构造函数;

LOCAL_VARIABLE:局部变量

ANNOTATION_TYPE:注解类型;

PACKAGE:包;

5、@Inherited

使用该Meta-annotation意思是该注解可以被自动继承。如果自定义注解声明了@Inherited,子类就会沿着继承树去查找有改表示的注解。除了在类上使用外,用在其他地方的都不起作用。只能在继承的情况下起作用,如果实现一个借口@Inherited也是不起作用的。

6、@Documentd

Indicates that annotations with a type are to be documented by javadoc and similar tools by default。

暂时写这些,待更新,如有错误请望轻拍^_^!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值