学习视频来源:B站UP主-遇见狂神说
注解与反射 1. 出现在方法上一行的@xxx就是注解,比如“重写”注解@Override @Override,表示一个方法打算重写超类中的另一个方法;
@Deprecated,表示不鼓励使用该方法,已过时的;
@SuppressWarnings,用来抑制编译时的警告信息,这个需要添加参数,参数是已定义的,根据选择使用;
以上都是内置注解。
元注解的作用就是负责注解其他注解。
@Target,用于描述注解的使用范围/被描述的注解可以用在什么地方;
@Retention,表示注解在什么时候是有效的,用于描述注解的生命周期;
@document,说明该注解将被生成在javaDoc中;
@Inherited,说明子类可以继承父类中的这个注解。
import java.lang.annotation.*;
// 元注解
public class Test02 {
@MyFirstAnnotation
public void test() {
}
// 定义一个注解
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME) // runtime > class > source
@documented
@Inherited
@interface MyFirstAnnotation {
}
}
3. 自定义注解
import java.lang.annotation.*;
// 元注解
public class Test02 {
// 注解可以显示赋值。如果没有默认值default,我们就要必须给注解赋值
@MyFirstAnnotation(age = 24, name = "荆轲")
public void test() {
}
@MySecondAnnotation("荆轲")
public void test1() {
}
// 定义一个注解
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME) // runtime > class > source
@interface MyFirstAnnotation {
// 注解的参数: 参数类型 + 参数名()
String name() default "狂神";
int age();
int id() default -1; // 如果默认值为-1,代表不存在
String[] schools() default {"北大", "清华"};
}
// 如果只有一个参数,建议使用value()
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MySecondAnnotation {
String[] value();
}
}
4. 反射机制
动态语言:在运行时可以根据某些条件改变自身的结构。
静态语言:运行时结构不可变。



