@Target(value=ElementType.METHOD) //意味着注解只能用在方法前面@Retention(RetentionPolicy.RUNTIME) //注解在运行时有效,即可以被反射读取public @interface My { //注解内包含的是参数的信息,不是方法,比如定义了一个String类型的name变量 String name() default ""; //加默认值,通常为0或空字符串,默认值为-1表示不存在 int age() default 0; int id() default -1; //定义一个数组 String[] s() default {"me","you"};}

value值可以定义为一个数组,以下表示可以在方法和类前使用注解

@Target(value= {ElementType.METHOD,ElementType.TYPE})public @interface my2{}

如果注解里只有一个参数,通常定义为value

@Target(value= {ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface My2 { //如果注解里只有一个参数,通常定义为value String value() default "";}

main

public class Demo { @My(age=19,name="me",id=10,s= {"it","that"}) //显示指定相应的值,可通过反射读取 public void test() { } //注解只有一个参数时 @My2(value="aaa")//或者 @My2("ada") public void test2() { } public static void main(String[] args) { }}