JavaSE 自定义注解
1.什么是注解:
注解就是一些特殊的接口
(百度百科)从JDK5开始,Java增加对元数据的支持,也就是注解,注解与注释是有一定区别的,可以把注解理解为代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,并执行相应的处理。通过注解开发人员可以在不改变原有代码和逻辑的情况下在源代码中嵌入补充信息。
2.常见的注解
@Override用来标记有几成关系的类
@SupressWarining压制警告
@Deprecated 过期生命
还有两种可以在自定义注解上注解;
@Target(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
}
@Rentention(RententionPolicy.*)自定义注解注解可以保留到什么
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//在运行期间依旧存在
}
3.注解的定义方法
public @interface 注解名{
Type name() default n;//表示是什么类型的注解参数,初始值是多少,当然也可以不写
}
4.实际定义一个注解
@Target({ElementType.Type,ElementType.Metod})
@Retention(RetentionPolicy.RUNTiME)
public @interface Measurement{
int group() default 10;
int iterations(); default 1000;
}