java 注解

    技术2024-10-06  58

      注解为我们在开发过程中,将元数据与源代码文件结合在一起,而不需要在外部文档中进行额外的设置。例如配置信息、接口文件、XML文件等。它使得代码更加干净易读,并且拥有编译期的类型检查,减轻了编写样板代码的负担。

     

    定义注解

    @Target(ElementType.METHOD)         //注解应用于什么地方(方法、域)

    @Retention(RetentionPolicy.RUNTIME)        //注解在什么级别可用(源代码、类文件、运行时)public @interface UseCase{    int  num();    String m();    String n() default "hello";     //默认值    String p() default "year"; }

     

    将方法注解为用例

    public class Utils{ 

    @UseCase(    num = 100,    m = "java test",    n = "hello world!",    p = "Year  2011")

    public static void CaseMethod1(String describe) { ... }

     

    @UseCase(    num = 101,    m = "java test2",    n = "hello world!2",    p = "Year  2012")

    public static void CaseMethod2(String describe) { ... }

     

    @UseCase(    num = 102,    m = "java test3",    n = "hello world!3",    p = "Year  2013")

    public static void CaseMethod3(String describe) { ... }

    }

     

    注解的元素在使用时表现为名——值对的形式,并需要至于@UseCase声明的括号内。

    注解处理器

    import java.lang.reflect.*;

    public class Test {   public static void main(String[] args) throws Exception {      Class cl = Utils.class;      for (Method m : cl.getDeclaredMethods()) {

               UseCase uc  = m.getAnnotation(UseCase.class);

               if(uc != null){

                   System.out.println("num = " + uc.num() + "  m = " + uc.m());

                   UseCase.remove(new Integer(uc.num()));

               }

            }

         }}

    最新回复(0)