内置注解
- @Override 重写的注解
- @Deprecated 一般不推荐程序员使用,但是可以使用,或者拥有更好的替代
- @SuppressWarnings(value = {xxx}) 镇压警告,可以放在方法上、类上、字段上、构造器上
自定义注解
import java.lang.annotation.*;
public class Test02 {
@MyAnnotation
public void test(){}
}
//定义一个注解
//@Target 注解的作用域
//ElementType.METHOD 表示可以在方法上有效放在其他地方就无效
//ElementType.TYPE 表示可以在类上有效,但在其他地方无效
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention 表示注解的有效期
//RetentionPolicy.RUNTIME 表示该注解在运行时之前都效果
//RetentionPolicy.CLASS 表示该注解在编译为class文件之前都有效
//RetentionPolicy.SOURCE 表示该注解在源码的时候才有效果,即未编译前
//有效期Runtime>Class>Source
@Retention(value = RetentionPolicy.SOURCE)
//Documented 表示将注解生成到Javadoc(java文档)里面
@Documented
//Inherited 表示子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
带参数的自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Test03 {
//注解可以显示赋值,也可以使用default默认赋值,如果没有默认赋值,就必须显示赋值
//赋值的时候没有顺序
@MyAnnotation2(age = 18,name = "O(∩_∩)O")
public void test(){}
@MyAnnotation3("(。・∀・)ノ゙")
public void test02(){}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数 : 参数类型 + 参数名();
String name() default "";
int age() default 0;
int id() default -1;//如果默认值为-1,代表不存在
String[] schools() default {"西部开源","清华大学"};
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
//如果只有一个参数,可以使用value命名,这样可以在赋值的时候省略参数名
String value();
}