注解
1 什么是注解(Annotation)
public class Test01 extends Object{
//@Override重写的注解
@Override
public String toString() {
return "Test01{}";
}
}
2 内置注解
2.1 @Override
@Override重写的注解
@Override
public String toString() {
return "Test01{}";
}
2.2 @Deprecated
@Deprecated 不推荐程序员使用,但是可以使用,存在更好的方法.
@Deprecated
public static void test(){
System.out.println("Test01");
}
2.3 @SuppressWarnings
@SuppressWarnings 镇压警告,平时写代码不建议镇压警告。
@SuppressWarnings("all")
public static void test02(){
List list = new ArrayList();
}
3 元注解
元注解作用:负责注解其他注解。重点掌握,@Target,@Retention
3.1 定义一个注解
@interface MyAnnotation {
}
3.2 @Target
@Target 表示我们的注解可以用在哪些地方
//Target注解的作用:注解自定义的interface注解
//只能在方法,类上使用
@Target({ElementType.METHOD,ElementType.TYPE})
@interface MyAnnotation {
}
3.3 @Retention
@Retention用以描述注解的生命周期
SOURCE源码级别,CLASS编译之后,
RUNTIME运行时(用的最多)
自定义的类一般都写RUNTIME
注解在什么阶段有效
//runtime>class>source
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
}
3.4 @Documented
@Documented 表示是否将我们的注解生成在JavaDoc中。
//Documented 表示是否将我们的注解生成在JavaDoc中
@Documented
@interface MyAnnotation {
}
3.5 @Inherited
@Inherited 子类可以继承父类的注解
//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation {
}
//Target注解的作用:注解自定义的interface注解
//只能在方法,类上使用
@Target({ElementType.METHOD,ElementType.TYPE})
//Retention表示注解在什么阶段有效
//runtime>class>source
@Retention(RetentionPolicy.RUNTIME)
//Documented 表示是否将我们的注解生成在JavaDoc中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
//定义一个注解
@interface MyAnnotation {
}
4 自定义注解
此时并未给注解赋默认值,因此在类或方法上使用该注解时得传入一个值。
public class Test03 {
@MyAnnotation1(name = "韩立")
public void test(){
}
}
//自定义注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation1 {
//注解的参数:参数类型+参数名+();
String name();
}@interface MyAnnotation1 {
//注解的参数:参数类型+参数名+();
String name();
}
此时注解默认值为空,在类或方法上使用该注解时可不用传入一个值。
public class Test03 {
@MyAnnotation1()
public void test(){
}
}
//自定义注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation1 {
//注解的参数:参数类型+参数名+();
String name() default " ";
}
public class Test03 {
@MyAnnotation1()
public static void test(){
}
@MyAnnotation2(value = "hh")
public static void test2(){
}
public static void main(String[] args) {
test();
}
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
自定义注解
@interface MyAnnotation1 {
//注解的参数:参数类型+参数名+();并不是方法
String name() default " ";
int age() default 0;
int id() default -1;//若默认值为-1,代表不存在
String [] school() default {"清华"};
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
//自定义注解
@interface MyAnnotation2 {
String value();
}
;//若默认值为-1,代表不存在
String [] school() default {“清华”};
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
//自定义注解
@interface MyAnnotation2 {
String value();
}