zoukankan      html  css  js  c++  java
  • 005-java的Annotation

    一、概述

      Annotation,JDK1.5开始提供

    二、基本定义

    public @interface HelloWorld {
    }

    1、使用@Interface定义,名称大写

    2、使用@Target修饰能放到那些类属性上,不写是能修饰任何java上

    3、元注解RetentionPolicy,表明注解的生命周期:

      1、SOURCE:在原文件中有效,被编译器丢弃。 
      2、CLASS:在class文件有效,可能会被虚拟机忽略。 
      3、RUNTIME:在运行时有效。

    4、成员,在注解中定义【不能是类类型,对象类型等,但是Class可以】

    public String name();

    增加缺省值 

    public String name() default "helloworld";

    如果只有一个成员并且是value,在使用时可以省略,直接写值。

    5、使用

    @HelloWorld(name = "nihao1")
    public class TestBean {
        @HelloWorld(name = "nihao2")
        private String name;
    
        @Override
        @HelloWorld(name = "nihao3")
        public String toString() {
         System.out.println("zhixing");
    return "TestBean [name=" + this.name + "]"; } }

    三、主要作用

    1、针对以上不做任何处理其实没有任何用处

    2、解析Annotation,然后处理问题

    public class Parser {
        public void parse(Object obj, String methodName) {
            Method[] ms = obj.getClass().getMethods();
            for (Method m : ms) {
                if (m.getName().equals(methodName)) {
                    if (m.isAnnotationPresent(HelloWorld.class)) {
                        HelloWorld hw = m.getAnnotation(HelloWorld.class);
                        try {
                            System.out.println("before...");
                            m.invoke(obj, null);
                            System.out.println("after...");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    3、Annotation处理的主要方法

    4、可以取代xml配置 

  • 相关阅读:
    node之body-parser的使用
    node解决跨域问题
    node之post提交上传
    HDU 6397(容斥原理)
    HDU 3374(最小最大表示法+KMP)
    HDU 6396(优先队列+思维)
    HDU 6395(矩阵快速幂)
    HDU 6370(并查集)
    HDU 6356(线段树)
    HDU 6354(计算几何)
  • 原文地址:https://www.cnblogs.com/bjlhx/p/9135774.html
Copyright © 2011-2022 走看看