Annotation + Enum

Annotation + Enum

One, enumeration

  1. Enumeration definition?

    Enumeration: enumeration The keyword enum, which represents a fixed value in some programs, is a type proposed after Java 5.0.

    Enumeration is to enumerate the fixed values ​​in the program.

  2. Create an enum?
    //和类对照着看
    //枚举本身不是类,但是我们可以看作是一个类来使用
    class A{
          
          }
    
    //枚举最大得特征就是属性全部大写
    enum A{
          
          
        RED,YELLOW,GREEN;
    }
    
  3. The use of enumeration?
    1. Enumeration is passed into switch case

      	@Test
          public void testEnum(){
              
              
              System.out.println(Color.RED);
              Color c = Color.RED;
              switch (c){
              
              
                  case GREEN:
                      System.out.println("绿灯");break;
                  case RED:
                      System.out.println("红灯");break;
                  case YELLOW:
                      System.out.println("黄灯");break;
              }
              System.out.println(Color.valueOf("RED")==Color.RED);
              System.out.println(Color.values()[0]+"\t"+Color.values()[1]+"\t"+Color.values()[2]);
              Color.RED.show();
          }
          
      
    2. valueOf(“”): Convert the string to the corresponding enumeration type

    3. values()[0]: Put the value of the enumeration into the form of an array, and return the first one

    4. Enumeration is to enumerate all the possibilities, the external can no longer be new, because the construction method of enumeration is privately modified

    5. The attributes in the enumeration, the type is the enumeration itself modifier public static final

    6. In addition, the toString() method of the enumeration has been rewritten, and the string obtained by printing the enumeration property directly

  4. Enumerated applications?
    1. The framework is the same, but the individual attributes are different, which can be encapsulated as an enumeration

      package com.etoak.enums;
      
      public enum Teacher {
              
              
          WL("二爷","易途COREJAVA讲师","人气颇高的美女讲师,授课严谨细致、脉络清晰,讲解声情并茂,善于拓展延伸,亲和力强,对待教学认真负责,要求严格,循循善诱,平易近人,不厌其烦,细心讲解,经验丰富,深入浅出,逻辑性强,善于总结归纳重点和难点。负责Java核心技术的教学,是无数易途学员的启蒙老师")
          ,
          QP("薄老师","DB","四年开发经验,曾在胜利油田项目中负责数据库迁移,并在中国移动旗下咪咕阅读参与数据库方案设计,数据实时推送,还在建筑,金融,电商,智能警务等多个行业积累了Oracle丰富的实战经验,并将整个课程都与现实工作紧密结合起来,负责Oracle数据库教学。");
          private String name;
          private String title;
          private String info;
      
          Teacher(String name, String title, String info) {
              
              
              this.name = name;
              this.title = title;
              this.info = info;
          }
      
          public String getName() {
              
              
              return name;
          }
      
          public String getTitle() {
              
              
              return title;
          }
      
          public String getInfo() {
              
              
              return info;
          }
      }
      
    2. Can also be used to assemble response content

      /*
      响应返回的样子
      * {
      *   code:200 50900
      *   msg:"",
      *   data:{}
      *
      * class ETResponse{
      *   int code;
      *   String msg;
      *   Object data;
      *   setter/getter
      * }
      
      
      定义枚举 列举出所有可能性
      * enum  ETStatus{
      *       SUCCESS(200,"invoke success"),FAIL(300,"invoke fail"),
      *       SERVER_ERROR(500,"server error");
      *         int code;
      *       String msg;
      *   private ETStatus(int code,String msg){
      *   this.code = code;
      *   this.msg = msg;
      *
      *   }
      *       getter..
      *}
      
      
      * StudentController{
      *   public ETResponse queryAllSchs(){
      *       List<School> schs = n....
              ETResponse response = new ETResponse();
              response.setCode(SUCCESS/FAIL/ERROR/..)200
              resposne.setCode(ETStatus.SUCCESS.getCode())
              response.setMsg()
              response.setData(变化);
      *  }
      * }
      * }
      

2. Annotation

  1. Introduction to annotations?
    1. Annotation keyword @interface used when creating Annotation
    2. Generally written on: class, attribute, method, parameter
    3. The annotation includes: the annotation type itself and the handler of the response
  2. The annotations you have seen so far?
    1. Mybatis

      @Parm: Set the key name for the assembled map in the output method parameter

      @Alias: Give the class an alias

    2. Servlet

      @WebServlet: Hot deployment

      @WebFIlter: filter

      @WebListener: listener

    3. Spring

      1. Create the object:

        @Component、@Controller、@Service、@Repository

      2. Assigning a value to the attribute:

        @Autowired + @Qulifier @Resource @Value

      3. @Configration @ConponentScan

      4. @RequstMapping (intercept request), @ResponseBody (assemble response content into json format)

    4. Junit

      @Test: unit test

  3. From the annotations under the Java.lang.annotation package

    The following annotations are for annotations. Load the above annotations

    1. @Target:表示注解可以用在哪些程序元素上
        //这里就是枚举
        value=ElementType.METHOD  方法
        	 =ElementType.FIELD  属性
        	 =ElementType.TYPE  其他类、接口
             =ElementType.PARAMETER  参数
    
    2. @Retention:注解的保留策略
        	一般注解写在源码中 编译之后保存到class文件中,但是运行期间,JVM加载类时,会把注解信息擦除
        value=RetentionPolicy.SOURCE  保存在源码中(.java文件)
        	 =RetetnionPolicy.CLASS   class文件 默认的
        	 =RetentionPolicy.RUNTIME   运行时加载
        
    3. @Document:是否把注解信息生成到API文档中
        
    4. @Override:重写注解,此注解的保留策略必然是SOURCE
        因为它只是在编译时检查是否完成重写,编译之后不需要存在了
    
    
  4. Custom annotations?
    public @interface Etoak{
          
          
        //注解中的属性  default给默认值
        Stirng value() default "";
    }
    
    //使用时
    1. value属性
        @Etoak("haha") 此处就是给value属性赋值 
        value可以省略:如果注解属性名字是value,则在使用注解给value赋值时 可以省略value
    
    2. 注解中可以放枚举
        RequestMethod.GET:枚举,表示可以接收什么请求 可以是个数组 表示接收多个请求
        @RequstMapping(value="query",method={
          
          RequestMethod.GET,RequestMethod.POST})
            
    3. 注解中可以放注解
            
        @WebServlet(value="/stu",name="xxx",
            initParams ={
          
          @WebInitParam(name="ContextConfigLocation",
            value="/WEB-INF/applicationContext.xml")} )
        
            
            initParams属性,放置的servlet初始化参数
            
            相当于:
    <servlet>
        <servlet-name>xxx</servlet-name>
        <servlet-class>Test</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </init-param>
    </servlet>
            
     <servlet-mapping>
        <servlet-name>xxx</servlet-name>
        <url-pattern>/stu</url-pattern>
    </servlet-mapping> 
    
  5. Handwritten Junit test class

    The principle of Junit unit testing:

    When we add @Test to a method, a main method will be triggered, that is to say, @Test annotation contains a main method

    step:

    1. First of all, we must first obtain the Class object of the current class.

    2. Then get all the methods of this Class object cls.getDeclaredMethods()

    3. Get annotations on all methods getDeclaredAnnotations

      The annotations that need to be used are the above annotations from the java.lang.annotation package

      Add @Retention(RUNTIME) to set the retention policy to run time

    4. To determine whether the annotation is a custom annotation, call invoke(new XXX()) if necessary

      Here new XXX() means to create an object with a main method

     public static void main(String[] args) throws Exception{
          
          
            //main
            Class cls = Test.class;
            Annotation [] ans = cls.getDeclaredAnnotations();
            for(Annotation an:ans){
          
          
                if(an.annotationType()==Etoak.class){
          
          
                    //1.created
                    Object obj = cls.newInstance();
                    //2.init
                    Method[] ms = cls.getDeclaredMethods();
                    for(Method m:ms){
          
          
                        Annotation[] as = m.getDeclaredAnnotations();
                        for(Annotation a:as){
          
          
                            if(a.annotationType() ==PostConstruct.class){
          
          
                                m.invoke(obj);
                            }
                            //doSth..
                            if(a.annotationType()==PreDestroy.class){
          
          
                                m.invoke(obj);
                            }
                        }
                    }
                }
            }
    

Guess you like

Origin blog.csdn.net/G7581/article/details/115018767