• Java自定义注解(1)


    Java注解简介

    1. Java注解(Annotation)

       Java注解是附加在代码中的一些元信息,用于一些工具在编译、

       运行时进行解析和使用,起到说明、配置的功能。 

       注解相关类都包含在java.lang.annotation包中。

    2. Java注解分类

      2.1 JDK基本注解 

      2.2 JDK元注解 

      2.3 自定义注解  

    3. JDK基本注解

      3.1 @Override

          重写

      3.2 @Deprecated

          已过时

      3.3 @SuppressWarnings(value = "unchecked") 

          压制编辑器警告 

    Java元注解  

    作用:元注解用于修饰其他的注解 

    @Retention定义注解的保留策略 

          @Retention(RetentionPolicy.SOURCE)             //注解仅存在于源码中,在class字节码文件中不包含 

          @Retention(RetentionPolicy.CLASS)              //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,

          @Retention(RetentionPolicy.RUNTIME)            //注解会在class字节码文件中存在,在运行时可以通过反射获取到

    @Target指定被修饰的Annotation可以放置的位置(被修饰的目标)

          @Target(ElementType.TYPE)                      //接口、类

          @Target(ElementType.FIELD)                     //属性 

          @Target(ElementType.METHOD)                    //方法 

          @Target(ElementType.PARAMETER)                 //方法参数 

          @Target(ElementType.CONSTRUCTOR)               //构造函数 

          @Target(ElementType.LOCAL_VARIABLE)            //局部变量 

          @Target(ElementType.ANNOTATION_TYPE)           //注解 

          @Target(ElementType.PACKAGE)                   // 

          注:可以指定多个位置,例如: 

    @Target({ElementType.METHOD, ElementType.TYPE}),也就是此注解可以在方法和类上面使用 

    @Inherited指定被修饰的Annotation将具有继承性 

    @Documented指定被修饰的该Annotation可以被javadoc工具提取成文档. 

    自定义注解 

    注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类)标记Annotation: 没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息  

    元数据Annotation: 

        包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据; 

    如何自定义注解? 

    使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是: 

       Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型,

       而且我们还可以使用default关键字为这个成员变量设定默认值;

    注意:只有名字为value”属性,赋值时可以省略属性名

    案例一(获取类与方法上的注解值):

     TranscationModel

    1 package com.ssm.annotation.p1;
    2 
    3 public enum  TranscationModel {
    4     Read, Write, ReadWrite
    5 }
    MyAnnotation1 
     1 package com.ssm.annotation.p1;
     2 
     3 import java.lang.annotation.*;
     4 
     5 /**
     6  * MyAnnotation1注解可以用在类、接口、属性、方法上
     7  * 注解运行期也保留
     8  * 不可继承
     9  */
    10 @Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
    11 @Retention(RetentionPolicy.RUNTIME)
    12 @Documented
    13 public @interface MyAnnotation1 {
    14     String name();
    15 }
    Demo1 
     1 package com.ssm.annotation.p1;
     2 
     3 import com.ssm.annotation.p2.MyAnnotation2;
     4 import com.ssm.annotation.p3.MyAnnotation3;
     5 
     6 @MyAnnotation1(name = "abc")
     7 public class Demo1 {
     8 
     9     @MyAnnotation1(name = "xyz")
    10     private Integer age;
    11 
    12     @MyAnnotation2(model = TranscationModel.Read)
    13     public void list() {
    14         System.out.println("list");
    15     }
    16 
    17     @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write})
    18     public void edit() {
    19         System.out.println("edit");
    20     }
    21 }
    Demo1Test 
     1 package com.ssm.controllerTest;
     2 
     3 import com.ssm.annotation.p1.*;
     4 import com.ssm.annotation.p2.MyAnnotation2;
     5 import com.ssm.annotation.p3.MyAnnotation3;
     6 import org.junit.Test;
     7 
     8 
     9 public class Demo1Test {
    10     @Test
    11     public void list() throws Exception {
    12 //        获取类上的注解
    13         MyAnnotation1 annotation1 = Demo1.class.getAnnotation(MyAnnotation1.class);
    14         System.out.println(annotation1.name());//abc
    15 
    16 //        获取方法上的注解
    17         MyAnnotation2 myAnnotation2 = Demo1.class.getMethod("list").getAnnotation(MyAnnotation2.class);
    18         System.out.println(myAnnotation2.model());//Read
    19 
    20 
    21     }
    22 
    23     @Test
    24     public void edit() throws Exception {
    25         MyAnnotation3 myAnnotation3 = Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class);
    26         for (TranscationModel model : myAnnotation3.models()) {
    27             System.out.println(model);//Read,Write
    28         }
    29     }
    30 }

     

    案例二(获取类属性上的注解属性值)

    TestAnnotation 
     1 package com.ssm.annotation.p2;
     2 
     3 import java.lang.annotation.ElementType;
     4 import java.lang.annotation.Retention;
     5 import java.lang.annotation.RetentionPolicy;
     6 import java.lang.annotation.Target;
     7 
     8 
     9 //@Retention(RetentionPolicy.SOURCE)
    10 @Retention(RetentionPolicy.RUNTIME)
    11 @Target(ElementType.FIELD)
    12 public @interface TestAnnotation {
    13     String value() default "默认value值";
    14 
    15     String what() default "这里是默认的what属性对应的值";
    16 }
    MyAnnotation2 
     1 package com.ssm.annotation.p2;
     2 
     3 
     4 import com.ssm.annotation.p1.TranscationModel;
     5 
     6 import java.lang.annotation.*;
     7 
     8 @Target(ElementType.METHOD)
     9 @Retention(RetentionPolicy.RUNTIME)
    10 @Documented
    11 public @interface MyAnnotation2 {
    12     TranscationModel model() default TranscationModel.ReadWrite;
    13 }
    Demo2 
     1 package com.ssm.annotation.p2;
     2 
     3 
     4 public class Demo2 {
     5     @TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
     6     private static String msg1;
     7 
     8     @TestAnnotation("这就是value对应的值1")
     9     private static String msg2;
    10 
    11     @TestAnnotation(value = "这就是value对应的值2")
    12     private static String msg3;
    13 
    14     @TestAnnotation(what = "这就是what对应的值")
    15     private static String msg4;
    16 }
    Demo2Test 
     1 package com.ssm.controllerTest;
     2 
     3 import com.ssm.annotation.p2.Demo2;
     4 import com.ssm.annotation.p2.TestAnnotation;
     5 import org.junit.Test;
     6 
     7 
     8 public class Demo2Test {
     9     @Test
    10     public void test1() throws Exception {
    11         TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
    12         System.out.println(msg1.value());
    13         System.out.println(msg1.what());
    14     }
    15 
    16     @Test
    17     public void test2() throws Exception {
    18         TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
    19         System.out.println(msg2.value());
    20         System.out.println(msg2.what());
    21     }
    22 
    23     @Test
    24     public void test3() throws Exception {
    25         TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);
    26         System.out.println(msg3.value());
    27         System.out.println(msg3.what());
    28     }
    29 
    30     @Test
    31     public void test4() throws Exception {
    32         TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);
    33         System.out.println(msg4.value());
    34         System.out.println(msg4.what());
    35     }
    36 }

    案例三(获取参数修饰注解对应的属性值):

    IsNotNull 
     1 package com.ssm.annotation.p3;
     2 
     3 import java.lang.annotation.*;
     4 
     5 
     6 @Documented
     7 @Target({ElementType.PARAMETER})
     8 @Retention(RetentionPolicy.RUNTIME)
     9 public @interface IsNotNull {
    10     boolean value() default false;
    11 }
    MyAnnotation3 
     1 package com.ssm.annotation.p3;
     2 
     3 import com.ssm.annotation.p1.TranscationModel;
     4 
     5 import java.lang.annotation.*;
     6 
     7 @Target(ElementType.METHOD)
     8 @Retention(RetentionPolicy.RUNTIME)
     9 @Inherited
    10 @Documented
    11 public @interface MyAnnotation3 {
    12     TranscationModel[] models() default TranscationModel.ReadWrite;
    13 }
    Demo3 
     1 package com.ssm.annotation.p3;
     2 
     3 public class Demo3 {
     4 
     5     public void hello1(@IsNotNull(true) String name) {
     6         System.out.println("hello:" + name);
     7     }
     8 
     9     public void hello2(@IsNotNull String name) {
    10         System.out.println("hello:" + name);
    11     }
    12 }
    Demo3Test 
     1 package com.ssm.controllerTest;
     2 
     3 import com.ssm.annotation.p3.Demo3;
     4 import com.ssm.annotation.p3.IsNotNull;
     5 import org.junit.Test;
     6 
     7 import java.lang.reflect.Parameter;
     8 
     9 public class Demo3Test {
    10 
    11     @Test
    12     public void hello1() throws Exception {
    13         Demo3 demo3 = new Demo3();
    14         for (Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) {
    15             IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
    16             if (annotation != null) {
    17                 System.out.println(annotation.value());//true
    18             }
    19         }
    20     }
    21 
    22     @Test
    23     public void hello2() throws Exception {
    24         Demo3 demo3 = new Demo3();
    25         for (Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) {
    26             IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
    27             if (annotation != null) {
    28                 System.out.println(annotation.value());//false
    29             }
    30         }
    31     }
    32 }

    Aop自定义注解的应用

    MyLog 
     1 package com.ssm.annotation.springAop;
     2 
     3 import java.lang.annotation.ElementType;
     4 import java.lang.annotation.Retention;
     5 import java.lang.annotation.RetentionPolicy;
     6 import java.lang.annotation.Target;
     7 
     8 @Target(ElementType.METHOD)
     9 @Retention(RetentionPolicy.RUNTIME)
    10 public @interface MyLog {
    11     String desc();
    12 }
    MyLogAspect 
     1 package com.ssm.annotation.springAop;
     2 
     3 import org.aspectj.lang.JoinPoint;
     4 import org.aspectj.lang.annotation.Aspect;
     5 import org.aspectj.lang.annotation.Before;
     6 import org.aspectj.lang.annotation.Pointcut;
     7 import org.aspectj.lang.reflect.MethodSignature;
     8 import org.slf4j.Logger;
     9 import org.slf4j.LoggerFactory;
    10 import org.springframework.stereotype.Component;
    11 
    12 @Component
    13 @Aspect
    14 public class MyLogAspect {
    15     private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);
    16 
    17     /**
    18      * 只要用到了com.ssmAOP.MyLog这个注解的,就是目标类
    19      */
    20     @Pointcut("@annotation(com.ssm.annotation.springAop.MyLog)")
    21     private void MyValid() {
    22     }
    23 
    24     @Before("MyValid()")
    25     public void before(JoinPoint joinPoint) {
    26         MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    27         logger.debug("[" + signature.getName() + " : start.....]");
    28 
    29         MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
    30         logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:" + myLog.desc());
    31     }
    32 }
    LogController 
     1 package com.ssm.annotation.springAop;
     2 
     3 import org.springframework.stereotype.Component;
     4 
     5 @Component
     6 public class LogController {
     7 
     8     @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
     9     public void testLogAspect() {
    10         System.out.println("sout输出");
    11     }
    12 }
    LogControllerTest 
     1 package com.ssm.controllerTest;
     2 
     3 import com.ssm.BaseTestCase;
     4 import com.ssm.annotation.springAop.LogController;
     5 import org.junit.Test;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 
     8 
     9 
    10 public class LogControllerTest extends BaseTestCase {
    11     @Autowired
    12     private LogController logController;
    13 
    14     @Test
    15     public void testLogAspect(){
    16         logController.testLogAspect();
    17     }
    18 }

  • 相关阅读:
    BZOJ3566: [SHOI2014]概率充电器
    BZOJ5018: [Snoi2017]英雄联盟
    BZOJ4627: [BeiJing2016]回转寿司
    BZOJ4719: [Noip2016]天天爱跑步
    BZOJ1511: [POI2006]OKR-Periods of Words
    BZOJ4721: [Noip2016]蚯蚓
    BZOJ1922: [Sdoi2010]大陆争霸
    BZOJ2525: [Poi2011]Dynamite
    单选按钮 / 复选框 样式自定义
    HDU 产生冠军 2094
  • 原文地址:https://www.cnblogs.com/xcn123/p/11919344.html
Copyright © 2020-2023  润新知