@interface 和 interface 这两个是不一样的
public @interface xxx 定义注解类
public interface xxx 定义接口
自定义注解也就三件事
1、定义注解
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Test {
}
注:@Target 表示这个注解的作用目标
@Target(ElementType.TYPE) //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包
2、加注解到方法上,也可能是类上,变量上
public class Lx {
@Test
public static void l1() { }
public static void l2() { }
@Test
public static void l3() {
throw new RuntimeException("Liu");
}
public static void l4() { }
@Test
public static void l5() { }
public static void l6() { }
@Test
public static void l7() {
throw new RuntimeException("Xiao");
}
public static void l8() { }
} 2
3、使用注解
这就涉及到反射的东西,可以去查一下java反射机制
会写注解,会用反射调注解
public class RunTest {
public static void main(String[] args) throws Exception {
int passed = 0, failed = 0;
for (Method m : Class.forName(args[0]).getMethods()) {
if (m.isAnnotationPresent(Test.class)) { //if(方法有@Test注解)
try {
m.invoke(null);
passed++;
} catch (Throwable ex) { //方法里抛出异常
System.out.printf("Test %s failed: %s %n", m, ex.getCause());
failed++;
}
}
}
System.out.printf("Passed: %d, Failed %d%n", passed, failed);
}
}