前言
在了解了注解的相关定义以及内置注解后,我们将继续探索元注解和自定义注解。
1. 元注解
[1] 元注解的作用就是负责解释其他的注解,java定义了4个标准的meta-annitation类型,他们被用来提供对其他annotation类型的说明。
[2] 这些类型和它所支持的类在java.lang.annotation包中可以找到。
(@Target, @Retention, @Document, @Inherited)
<2.1>@Target: 用于描述注解的使用范围(即: 被描述的注解可以使用在什么地方)
例如: @Target(value = {ElementType.METHOD,ElementType.TYPE})
相关源码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
我们可以看到这个注解只有一个属性value,它的类型是ElementType[ ],这里就是用来表示能标注的地方
可以看到它是一个枚举类型
public enum ElementType {
//类,接口
TYPE,
//属性
FIELD,
//方法
METHOD,
//参数
PARAMETER,
//构造方法
CONSTRUCTOR,
//内部的局部变量
LOCAL_VARIABLE,
//注解类型
ANNOTATION_TYPE,
//包
PACKAGE,
//参数类型
TYPE_PARAMETER,
//能标注任何类型名称
TYPE_USE
}
<2.2> @Retention: 表示需要在什么级别保存该注解信息,用于描述声明周期
(SOURCE< CLASS<RUNTIME) ==> 源码<字节码<运行时,这每个时期都是循序渐进的,也表明了这个注解将在什么时期失效。(详情可参考注解@Retention)
例如: @Retention(value = RetentionPolicy.RUNTIME)
<2.3> @Document: 说明该注解将被包含在javadoc中
<2.4> @Inherited: 说明子类可以继承父类中的注解
(后面两个元注解较为少用,只需了解意思即可)
2. 自定义注解
在了解了元注解后,我们将实现自己定义注解。
- 使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口
- 分析:
- @interface用来声明一个注解,格式: public @interface 注解名{定义内容}
- 其中的每一个方法实际上是声明了一个配置参数
- 方法的名称就是参数的名称
- 返回值类型就是参数的类型(返回值只能是基本类型 Class,String,enum)
- 可以通过default来声明参数的默认值
- 如果只有一个参数成员,一般参数名为value
- 注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0作为默认值。
自定以注解的示例:
package com.gs.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定义注解
public class test03 {
// 注解可以显示赋值(如果没有默认值,我们就必须给注解赋值)
@MyAnnotation2(name = "zs")
public void test(){}
@MyAnnotation3("gs")
public void test2(){}
}
//可以标注在类和方法上
@Target({ElementType.TYPE,ElementType.METHOD})
//这个注解运行的时候还有效
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数: 注解类型 + 参数名()
String name() default "";
int age() default 0;
//如果默认值为-1,代表不存在
int id() default -1;
String[] schools() default {"野鸡大学","清华大学"};
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}
以上所学都是来源于B站up主狂神说java。