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
  • 相关阅读:
    Linux基础命令—clear
    Linux基础命令—mv
    Linux基础命令—rm
    Linux基础命令—cp
    Linux基础命令—touch
    Linux基础命令—tree
    C#获取设备话筒主峰值(实时音频输出分贝量)
    C# 获取基类或者接口的所有继承类方法
    RegisterAttached 两种绑定方式
    RijndaelManaged 加密
  • 原文地址:https://www.cnblogs.com/archie2010/p/1987355.html
Copyright © 2011-2022 走看看