博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java自定义注解
阅读量:3960 次
发布时间:2019-05-24

本文共 13243 字,大约阅读时间需要 44 分钟。

Java注解(Annotation)简介

java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。
注解相关类都包含在java.lang.annotation包中。

Java注解分类

JDK基本注解

不需要编写代码,jdk自带
1.@Override
重写
2.@Deprecated
已过时
3.@SuppressWarnings(value = “unchecked”)
压制编辑器警告(eclipse 现在已少见)
JDK元注解
作用:元注解用于修饰其他的注解

@Retention:定义注解的保留策略@Retention(RetentionPolicy.SOURCE)             //注解仅存在于源码中,在class字节码文件中不包含@Retention(RetentionPolicy.CLASS)              //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,@Retention(RetentionPolicy.RUNTIME)            //注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Inherited:指定被修饰的Annotation将具有继承性 @Documented:指定被修饰的该Annotation可以被javadoc工具提取成文档.

现在一般来说比较常用

@Retention:定义注解的保留策略

package com.zxp.ssm.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author笑笑 * @site www.xiaoxiao.com * @company  * @create 2019-12-25 19:18 *///@Retention(RetentionPolicy.SOURCE)//不会编译到target  class@Retention(RetentionPolicy.RUNTIME)//(通过反射方法获取)注解会在class字节码文件中存在,在运行时可以通过反射获取到@Target(ElementType.TYPE)//@Retention(RetentionPolicy.CLASS)//默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,public @interface Demo {
}

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

@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}),也就是此注解可以在方法和类上面使用

@Target({ElementType.TYPE})

作用于接口、类
在这里插入图片描述
在这里插入图片描述
@Target({ElementType.TYPE,ElementType.FIELD})
作用于接口、类,属性
在这里插入图片描述
在这里插入图片描述
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
作用于接口、类,属性,方法
在这里插入图片描述
在这里插入图片描述
等等。。。
@Inherited:指定被修饰的Annotation将具有继承性
没有被@Inherited注解标记的注解,就不具有继承特性,在子类中获取不到父类的注解
@Inherited注解继承概念跟我们理解的面向对象继承概念不一样,它只作用于子类与父类之间的继承
@Inherited注解标记的注解,在使用时,如果父类和子类都使用的注解是同一个,那么子类的注解会覆盖父类的注解
在这里插入图片描述
自定义注解
注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类):
标记Annotation: 没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息
元数据Annotation: 包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据;
如何自定义注解?
使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是:
Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型,而且我们还可以使用default关键字为这个成员变量设定默认值;
注意:只有名字为“value”属性,赋值时可以省略属性名

代码演示

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

TranscationModel

package com.zxp.ssm.annotation.p1;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 19:48 * enum 接口方法实现列举 */public enum TranscationModel {
Read, Write, ReadWrite}

MyAnnotation1

package com.zxp.ssm.annotation.p1;import java.lang.annotation.*;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:11 * MyAnnotation1注解可以用在类、接口、属性、方法上 * 注解运行期也保留 * 不可继承 */@Target({
ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})//可以用在类、接口、属性、方法上@Retention(RetentionPolicy.RUNTIME)//注解会在class字节码文件中存在,在运行时可以通过反射获取到@Documentedpublic @interface MyAnnotation1 {
String name();}

MyAnnotation2

package com.zxp.ssm.annotation.p1;import java.lang.annotation.*;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:12 *MyAnnotation2注解可以用在方法上 *  注解运行期也保留 *  不可继承 */@Target(ElementType.METHOD)//可以用在方法上@Retention(RetentionPolicy.RUNTIME)//注解会在class字节码文件中存在,在运行时可以通过反射获取到@Documentedpublic @interface MyAnnotation2 {
TranscationModel model() default TranscationModel.ReadWrite;}

MyAnnotation3

package com.zxp.ssm.annotation.p1;import java.lang.annotation.*;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:12 * MyAnnotation3注解可以用在方法上 *注解运行期也保留 *可继承 */@Target(ElementType.METHOD)//可以用在方法上@Retention(RetentionPolicy.RUNTIME)//注解会在class字节码文件中存在,在运行时可以通过反射获取到@Inherited@Documentedpublic @interface MyAnnotation3 {
TranscationModel[] models() default TranscationModel.ReadWrite;}

Demo1

package com.zxp.ssm.annotation.p1;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:13 * 获取类与方法上的注解值 */@MyAnnotation1(name = "abc")public class Demo1 {
@MyAnnotation1(name = "xyz") private Integer age; @MyAnnotation2(model = TranscationModel.Read) public void list() {
System.out.println("list"); } @MyAnnotation3(models = {
TranscationModel.Read, TranscationModel.Write}) public void edit() {
System.out.println("edit"); }}

Demo1Test

package com.zxp.ssm.annotation.p1;import org.junit.Test;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:13 */public class Demo1Test {
@Test public void list() throws Exception {
// 获取类上的注解 反射 MyAnnotation1 annotation1 = Demo1.class.getAnnotation(MyAnnotation1.class); System.out.println(annotation1.name());//abc// 获取方法上的注解 MyAnnotation2 myAnnotation2 = Demo1.class.getMethod("list").getAnnotation(MyAnnotation2.class); System.out.println(myAnnotation2.model());//Read } @Test public void edit() throws Exception {
MyAnnotation3 myAnnotation3 = Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class); for (TranscationModel model : myAnnotation3.models()) {
System.out.println(model);//Read,Write } }}

测试list

在这里插入图片描述
测试edit
在这里插入图片描述
案例二(获取类属性上的注解属性值)
TestAnnotation

package com.zxp.ssm.annotation.p2;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:15 *///@Retention(RetentionPolicy.SOURCE)@Retention(RetentionPolicy.RUNTIME)//注解会在class字节码文件中存在,在运行时可以通过反射获取到@Target(ElementType.FIELD)//可以用在属性上public @interface TestAnnotation {
String value() default "默认value值"; String what() default "这里是默认的what属性对应的值";}

Demo2

package com.zxp.ssm.annotation.p2;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:16 * * 除了能获取类属性上的注解属性值 * 当没有填注解属性的时候默认加上value */public class Demo2 {
@TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1") private static String msg1; @TestAnnotation("这就是value对应的值1") private static String msg2; @TestAnnotation(value = "这就是value对应的值2") private static String msg3; @TestAnnotation(what = "这就是what对应的值") private static String msg4;}

Demo2Test

package com.zxp.ssm.annotation.p2;import org.junit.Test;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:17 */public class Demo2Test {
@Test public void test1() throws Exception {
TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class); System.out.println(msg1.value()); System.out.println(msg1.what()); } @Test public void test2() throws Exception{
TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class); System.out.println(msg2.value()); System.out.println(msg2.what()); } @Test public void test3() throws Exception{
TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class); System.out.println(msg3.value()); System.out.println(msg3.what()); } @Test public void test4() throws Exception{
TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class); System.out.println(msg4.value()); System.out.println(msg4.what()); }}

测试test1// 获得msg1属性上的值

在这里插入图片描述
测试test2// 获得msg2属性上的值
在这里插入图片描述
设置what为空
在这里插入图片描述
在这里插入图片描述
测试test3// 获得msg3属性上的值
在这里插入图片描述
测试test4// 获得msg4属性上的值
在这里插入图片描述
案例三(获取参数修饰注解对应的属性值):
IsNotNull

package com.zxp.ssm.annotation.p3;import java.lang.annotation.*;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:18 * 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空 */@Documented@Target({
ElementType.PARAMETER})//方法参数@Retention(RetentionPolicy.RUNTIME)//注解会在class字节码文件中存在,在运行时可以通过反射获取到public @interface IsNotNull {
boolean value() default false;}

Demo3

package com.zxp.ssm.annotation.p3;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:18 * 获取参数修饰注解对应的属性值 */public class Demo3 {
public void hello1(@IsNotNull(true) String name) {
System.out.println("hello:" + name); } public void hello2(@IsNotNull String name) {
System.out.println("hello:" + name); } public void hello3(@IsNotNull(true) String name,@IsNotNull String sex,@IsNotNull(true) String addr) {
System.out.println("hello:" + name); }}

Demo3Test

package com.zxp.ssm.annotation.p3;import org.junit.Test;import java.lang.reflect.Parameter;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:19 */public class Demo3Test {
@Test public void hello1() throws Exception {
Demo3 demo3 = new Demo3(); for (Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) {
IsNotNull annotation = parameter.getAnnotation(IsNotNull.class); if(annotation != null){
System.out.println(annotation.value());//true } } } @Test public void hello2() throws Exception {
Demo3 demo3 = new Demo3(); for (Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) {
IsNotNull annotation = parameter.getAnnotation(IsNotNull.class); if(annotation != null){
System.out.println(annotation.value());//false } } } @Test public void hello3() throws Exception {
Demo3 demo3 = new Demo3(); for (Parameter parameter : demo3.getClass().getMethod("hello3", String.class, String.class, String.class).getParameters()) {
IsNotNull annotation = parameter.getAnnotation(IsNotNull.class); if(annotation != null){
System.out.println(annotation.value());//true } } }}

测试hello1

在这里插入图片描述
测试hello2
在这里插入图片描述
测试hello3

在这里插入图片描述

Aop自定义注解的应用

MyLog

package com.zxp.ssm.annotation.springAop;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:22 */@Target(ElementType.METHOD)//方法@Retention(RetentionPolicy.RUNTIME)//注解会在class字节码文件中存在,在运行时可以通过反射获取到public @interface MyLog {
String desc();}

MyLogAspect

package com.zxp.ssm.annotation.springAop;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:21 */@Component@Aspectpublic class MyLogAspect {
private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class); /** * 现在 @Pointcut("@annotation(com.zxp.ssm.annotation.springAop.MyLog)") 凡是使用过MyLog都是我的目标类 * */ @Pointcut("@annotation(com.zxp.ssm.annotation.springAop.MyLog)") private void MyValid() {
}/*// 之前写的切面 @Around("execution(**..Service.*pager(..))") private void MyValid1() { }*/ /* * 凡是目标类都要进before这个方法 * */ @Before("MyValid()") public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature(); logger.debug("[" + signature.getName() + " : start.....]"); MyLog myLog = signature.getMethod().getAnnotation(MyLog.class); logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:"+myLog.desc()); }}

LogController

package com.zxp.ssm.annotation.springAop;import org.springframework.stereotype.Component;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:24 */@Componentpublic class LogController {
@MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例") public void testLogAspect(){
System.out.println("这里随便来点啥"); }// @MyLog(desc = "增加书籍")// public void bookAdd(){
// System.out.println("增加书籍");// }}

BaseTestCase

package com.zxp.ssm.annotation.p2;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:24 */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={
"classpath:applicationContext.xml"})public class BaseTestCase {
}

LogControllerTest

package com.zxp.ssm.annotation.springAop;import com.zxp.ssm.annotation.p2.BaseTestCase;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;/** * @author笑笑 * @site www.xiaoxiao.com * @company * @create 2019-12-25 20:25 */public class LogControllerTest extends BaseTestCase {
@Autowired private LogController logController; @Test public void testLogAspect(){
logController.testLogAspect(); }}

测试testLogAspect

在这里插入图片描述

转载地址:http://xurzi.baihongyu.com/

你可能感兴趣的文章
urllib2.urlopen超时问题
查看>>
魏兴国:深入浅出DDoS攻击防御
查看>>
使连续的参考文献能够中间用破折号连起来
查看>>
Discover Feature Engineering, How to Engineer Features and How to Get Good at It
查看>>
36辆车,6条跑道,无计时器,最少几次比赛可以选出前三
查看>>
matlab2012b与matlab7.1执行set(gca,'Yscale','log')之后画到的直方图结果居然不同
查看>>
回文题
查看>>
AJAX应用之注册用户即时检测
查看>>
File 类小结
查看>>
java除去字符串空格
查看>>
jsp 2.0标记文件
查看>>
Hibernate中Criteria的完整用法
查看>>
sql jsp
查看>>
spring beans beanfactory applicationcontext
查看>>
使用ORM工具进行数据访问
查看>>
使用ORM工具进行数据访问
查看>>
编译与部署Eclipse+Tomcat+MySQL+Liferay4.1.2
查看>>
POJ3728,The merchant(倍增LCA+分治)
查看>>
2019 ICPC Malaysia National,E. Optimal Slots(01背包变形)
查看>>
洛谷P1638 逛画展(双向队列)
查看>>