zoukankan      html  css  js  c++  java
  • Java注解(二)

    前面了解了注解的基本内容,这次来看一下自定义注解。

    自定义注解其实很简单,直接上代码:

    import java.lang.annotation.Documented;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.RetentionPolicy;
    
    
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    /*
     * 定义注解 Test
     * 注解中含有两个元素 id 和 description
     * description 元素 有默认值 "hello anntation"
     */
    public @interface Test {
        public int id();
        public String description() default "hello annotation";
    }

     根据上一篇对元注解的解释,我们知道:

    1. 这个注解可以用于方法
    2. JVM运行期间该注解都有效
    3. 该注解包含在 javadoc 中
    4. 该注解允许子类继承

     下面看下通过注解我们能取到什么

    public class TestMain {  
        /* 
         * 被注解的三个方法 
         */  
        @Test(id = 1, description = "hello methodA")  
        public void methodA() {  
        }  
      
        @Test(id = 2)  
        public void methodB() {  
        }  
      
        @Test(id = 3, description = "last method")  
        public void methodC() {  
        }  
      
        /* 
         * 解析注解,将类被注解方法 的信息打印出来 
         */  
        public static void main(String[] args) {  
            Method[] methods = TestMain.class.getDeclaredMethods();  
            for (Method method : methods) {  
                /* 
                 * 判断方法中是否有指定注解类型的注解 
                 */  
                boolean hasAnnotation = method.isAnnotationPresent(Test.class);  
                if (hasAnnotation) {  
                    /* 
                     * 根据注解类型返回方法的指定类型注解 
                     */  
                    Test annotation = method.getAnnotation(Test.class);  
                    System.out.println("Test( method = " + method.getName() + " , id = " + annotation.id() 
                            + " , description = " + annotation.description() + " )");
                }  
            }  
        }  
    } 

     上面的Demo打印的结果如下:

    Test( method = methodA , id = 1 , description = hello methodA )
    Test( method = methodB , id = 2 , description = hello annotation )
    Test( method = methodC , id = 3 , description = last method )

     上例其实也说明了,我们一般通过反射来取RUNTIME保留策略的注解信息。

  • 相关阅读:
    LeetCode: Copy List with Random Pointer
    LeetCode: Clone Graph
    LeetCode: Candy
    Database: Normal form
    Algorithm: cartesian tree
    【阿里云产品公测】云引擎ACE初体验
    【阿里云产品公测】Opensearch使用体验和评测
    【阿里云产品公测】阿里云OpenSearch初次使用评测
    【阿里云产品公测】OpenSearch初探
    【阿里云产品公测】弹性伸缩服务ESS之试用初体验
  • 原文地址:https://www.cnblogs.com/yejg1212/p/3188751.html
Copyright © 2011-2022 走看看