1 概念
Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。
2 标准注解
常见的有:
@Override 重写的注解
@Deprecated 不鼓励使用的元素
@SuppresWarnings() 抑制警告
3 元注解
负责注解其他注解
@Target:描述注解的使用范围
@Retention:表示需要在什么级别保存该注释信息,描述注解的生命周期,在源代码中(SOURCE)、类文件中(CLASS)或者运行时(RUNTIME)。
(SOURCE<CLASS<RUNTIME)
@Documented:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
使用示例:
// 自定义一个注解
// Document 表示是否将注解生成在Javadoc中
@Documented
// Retention 表示注解在何时有效 Runtime >class >sources
@Retention(RetentionPolicy.RUNTIME)
// Target表示注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
// 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
3 自定义注解
使用@interface定义注解时,自动继承了java.lang.annotation.Annotation接口
- 格式:
public @interface 注解名{定义内容}
import java.lang.annotation.*;
public class test01 {
// 注解可以显示赋值,若有默认值可以不写,若没有默认值则必须给注解赋值
@MyAnnotation(age = 1)
public void test() {
}
// 自定义一个注解 MyAnnotation
// Document 表示是否将注解生成在Javadoc中
@Documented
// Retention 表示注解在何时有效 Runtime >class >sources
@Retention(RetentionPolicy.RUNTIME)
// Target表示注解可以用在哪些地方
@Target({ElementType.METHOD,ElementType.TYPE})
// 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
// 注解的参数:参数类型+参数名();
// 使用default声明参数的默认值
String name() default "";
int age();//无默认值
}
// 自定义一个注解 MyAnnotation2
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
@Inherited
@interface MyAnnotation2{
// 如果只有一个参数成员,一般参数名为value
String value();
}
}