zoukankan      html  css  js  c++  java
  • 自定义注解annotation

    自定义的注解MyAnnotation.java

    /**
    * 自定义的方法描述注解
    *
    @author archie2010
    * since 2011-3-17 下午06:20:29
    */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    public @interface MyAnnotation {

    public String desc1() default "no description";

    public String desc2() default "no description";
    }

    * 元注解@Target,@Retention,@Documented,@Inherited

    *      @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括:

    *          ElemenetType.CONSTRUCTOR 构造器声明

    *          ElemenetType.FIELD 域声明(包括 enum 实例)

    *          ElemenetType.LOCAL_VARIABLE 局部变量声明

    *          ElemenetType.METHOD 方法声明

    *          ElemenetType.PACKAGE 包声明

    *          ElemenetType.PARAMETER 参数声明

    *          ElemenetType.TYPE 类,接口(包括注解类型)或enum声明

    *      @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:

    *          RetentionPolicy.SOURCE 注解将被编译器丢弃

    *          RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃

    *          RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。    

    *      @Documented 将此注解包含在 javadoc 中

    *      @Inherited 允许子类继承父类中的注解


    Person.java

    public class Person {

    @MyAnnotation(desc1
    ="方法描述1",desc2="方法描述2")
    public void add(Integer i){
    System.out.println(
    "---------");
    }
    }

    测试类

    TestAnnotation.java

    /**
    * Annotation测试
    *
    @author archie2010
    * since 2011-3-17 下午03:34:56
    */
    public class TestAnnotation {

    @SuppressWarnings(
    "unchecked")
    public static void main(String[] args) throws Throwable {
    //MyAnnotation myAnnotation=new Person().getClass().getMethod("add").getAnnotation(MyAnnotation.class);

    //获得有参方法Method时需要不定向参数Clazz...
    MyAnnotation myAnnotation=new Person().getClass().getMethod("add",Integer.class).
    getAnnotation(MyAnnotation.
    class);

    System.out.println(myAnnotation.desc1());
    System.out.println(myAnnotation.desc2());


    System.out.println(Integer.
    class.toString());
    System.out.println(Long.
    class.toString());
    if(Integer.class.toString().equals("class java.lang.Integer")){
    System.out.println(
    "------相等");
    }
    }
    }



    by archie
  • 相关阅读:
    paip.环境设置 mybatis ibatis cfg 环境设置
    paip。java 高级特性 类默认方法,匿名方法+多方法连续调用, 常量类型
    paip. java的 函数式编程 大法
    paip.函数方法回调机制跟java php python c++的实现
    paip.配置ef_unified_filter() failed ext_filter_module mod_ext_filter.so apache 错误解决
    paip. 解决java程序不能自动退出
    Paip.声明式编程以及DSL 总结
    paip. dsl 编程语言优点以及 常见的dsl
    paip.函数式编程方法概述以及总结
    paip.jdbc 连接自动释放的测试
  • 原文地址:https://www.cnblogs.com/archie2010/p/1987355.html
Copyright © 2011-2022 走看看