Java5.0学习笔记

Annotations

定义annotation类型

1.public @interface xxxxx{ //以@interface 表明这是一个annotation 类型

        int id(); //每个方法都是该annotation的一个element,不得有参数和抛出异常。

        String syposis();//返加类型:原始类型及String Class,enums annotations 及以这些类型作为基本类型的数组。

        String engineer() default "[unassigned]";//可以设定默认值。

}

使用

@xxxxx(

    id = 33,//每个element都以","分隔。

    syposis = "Enable dddd",

    engineer = "xxxx" //最后结尾没有符合。

)   //一般放在public static final等限定符前面。

public static void someMethod(){ }

<!--[if !supportEmptyParas]--> <!--[endif]-->

2.没有element annotation

public @interface xxNoElement{}

使用时可以省去后面的括号。

@xxNoElement() //也可以是@xxNoElement

public void someMethod(){}

<!--[if !supportEmptyParas]--> <!--[endif]-->

3.如果只有一个element 这个element的名称必须是value.

public @interface xxOneElement{

    String value();

}

使用

@xxOneElement( value = "vvvv")

//也可以是:@xxOneElement("vvvvvv")

public Class getSomeClass(){}

<!--[if !supportEmptyParas]--> <!--[endif]-->

在定义一个annotation时也可指定该annotation使用位置(method,field constructor package以及应该保持多长时间。

@Retention (RetentionPolicy.RUNTIME) //CLASS,RUNTIME,SOURCE

@Target (ElementType.METHOD)     //ANNOTATION_TYPE,CONSTRUCTOR,FIELD,LOCAL_VARIBALE,METHOD,PACHAGE,PARAMETER,TYPE

public @interface xxxx{

   

}

<!--[if !supportEmptyParas]--> <!--[endif]-->

运用@annotation

import java.lang.reflect.*;

<!--[if !supportEmptyParas]--> <!--[endif]-->

public class RunTests {

   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)) {

            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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值