public class Demo01 {
//注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
@MyAnnotation(age=17) //有参数名并布赋值
public void test(){}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
//注解的参数格式: 参数类型 参数名()
String name() default "";
int age();
int id() default -1; //如果默认值为1,代表不存在
String[] school() default {"清华大学","北京大学"};
}
public class Demo02 {
//注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
@MyAnnotation2("你好,世界") //没有参数名直接赋值
public void Test2(){}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
//不成文的规定,如果注解中参数只有一个,那么建议使用value命名,在调用时可以不写参数名,直接赋值
@interface MyAnnotation2{
String value();
}
注解的本质其实是一个接口,只是继承了注解类。
自定义注解(源文件)
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String name() default "张三";
int age();
}
反编译后的注解(.class文件编译后的注解)
import java.lang.annotation.Annotation;
public interface MyAnnotation
extends Annotation
{
public abstract String name();
public abstract int age();
}