public @interface xxx 自定义注解

@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); 

   } 

  } 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值