1. 什么是注解
注解是给程序看的,注释是给人看的。
2. 内置注解
// 什么是注解
public class Test01 extends Object {
// 重写的注解
@Override
public String toString() {
return super.toString();
}
// Deprecated, 不推荐程序员使用,但是可以使用,或者存在更好的方式
@Deprecated
public static void test01() {
System.out.println("Deprecated");
}
@SuppressWarnings("all")
public void test02() {
List<String> list = new ArrayList<>();
}
public static void main(String[] args) {
test01();
}
}
3. 元注解
public class Test02 {
public void test() {
}
}
// 定义一个注解
// Target,表示定义的注解可以用在什么地方
@Target(value = {ElementType.METHOD})
// Retention,表示定义的注解在什么地方还有效
// runtime>class>source
@Retention(RetentionPolicy.RUNTIME)
// 表示是否将定义的注解生产在JAVAdoc中
@Documented
// 子类可以继承父类的注解
@Inherited
@interface MyAnnotation {
}
4. 自定义注解
// 自定义注解
public class Test03 {
// 注解可以显示赋值,如果没有默认值,则必须给注解赋值
@MyAnnotation02(age = 18)
public void test01() {
}
@MyAnnotation03("qinjiang")
public void test02() {
}
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation02 {
// 注解的参数:参数类型 + 参数名 ();
String name() default "";
int age();
int id() default -1;
String[] schools() default {"清华", "北大"};
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation03 {
// 若只有一个参数且使用value(),则使用时可不写参数名value
String value();
}
参考
根据狂神注解视频学习
链接:https://www.bilibili.com/video/BV1p4411P7V3?p=4