核心注解类TestAnnotation.java
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//元注解
@Retention(RetentionPolicy.RUNTIME)
//注解可以应用于方法上和类上
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface TestAnnotation {
//属性(default 默认值)
String color() default "blue";
String value();
int[] arr();
TrafficLamp tl() default TrafficLamp.GREEN;
//注解属性
MetaAnnotation metaAnno() default @MetaAnnotation("sss");
Class clazz() default String.class;
}
方法上定义注解AnnotationMethodTest.java
package annotation;
import org.junit.Test;
//方法上定义注解
public class AnnotationMethodTest {
@Test
@TestAnnotation(value = "methodTest",arr = {1,2,3},tl = TrafficLamp.RED,metaAnno = @MetaAnnotation("abc"),clazz = Integer.class)
public void test_1(){
if(AnnotationTest.class.isAnnotationPresent(TestAnnotation.class)){
TestAnnotation ta = AnnotationTest.class.getAnnotation(TestAnnotation.class);
System.out.println(ta);
System.out.println(ta.getClass());
System.out.println(ta.value());
System.out.println(ta.arr().length);
System.out.println(ta.tl());
System.out.println(ta.metaAnno().value());
}
}
}
类上定义注解及测试类
package annotation;
import org.junit.Test;
//只有value属性声明的时候可以省略"value="
@TestAnnotation(value = "test",arr = {1,2,3},tl = TrafficLamp.RED,metaAnno = @MetaAnnotation("abc"),clazz = Integer.class)
public class AnnotationTest {
@Test
public void test_1() throws Exception{
if(AnnotationTest.class.isAnnotationPresent(TestAnnotation.class)){
TestAnnotation ta = AnnotationTest.class.getAnnotation(TestAnnotation.class);
System.out.println(ta);
System.out.println(ta.getClass());
System.out.println(ta.value());
System.out.println(ta.arr().length);
System.out.println(ta.tl());
System.out.println(ta.metaAnno().value());
}
AnnotationMethodTest amt = new AnnotationMethodTest();
if(amt.getClass().getMethod("test_1").isAnnotationPresent(TestAnnotation.class)){
TestAnnotation ta = amt.getClass().getMethod("test_1").getAnnotation(TestAnnotation.class);
System.out.println(ta);
System.out.println(ta.getClass());
System.out.println(ta.value());
System.out.println(ta.arr().length);
System.out.println(ta.tl());
System.out.println(ta.metaAnno().value());
}
}
}