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”属性,赋值时可以省略属性名

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

package com.ssm.annotation;

/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
public enum TranscationModel {
Read, Write, ReadWrite
}

  

package com.ssm.annotation;

import java.lang.annotation.*;

/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*
* MyAnnotation1注解可以用在类、接口、属性、方法上
* 注解运行期也保留
* 不可继承
*/
@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
String name();
}

  

package com.ssm.annotation;
/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/ import java.lang.annotation.*; @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
TranscationModel model() default TranscationModel.ReadWrite;
}

  

package com.ssm.annotation;
/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/ import java.lang.annotation.*; @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation3 {
TranscationModel[] models() default TranscationModel.ReadWrite;
}

  

package com.ssm.annotation;

/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
@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");
}
}

  

import com.ssm.annotation.*;
import org.junit.Test; /**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
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
}
}
}

  

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

package com.ssm.annotation2;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
//@Retention(RetentionPolicy.SOURCE)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestAnnotation {
String value() default "默认value值"; String what() default "这里是默认的what属性对应的值";
}

  

package com.ssm.annotation2;

/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
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;
}

  

import com.ssm.annotation2.Demo2;
import com.ssm.annotation2.TestAnnotation;
import org.junit.Test; /**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
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());
}
}

  

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

package com.ssm.annotation3;

import java.lang.annotation.*;

/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNotNull {
boolean value() default false;
}

  

package com.ssm.annotation3;

/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
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);
}
}

  

import com.ssm.annotation3.Demo3;
import com.ssm.annotation3.IsNotNull;
import org.junit.Test;
/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
import java.lang.reflect.Parameter; 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
}
}
}
}

Aop自定义注解的应用

package com.ssm.AOP;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
String desc();
}

  

package com.ssm.AOP;

import org.aspectj.lang.JoinPoint;
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 xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
@Component
@Aspect
public class MyLogAspect {
private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class); /**
* 只要用到了com.ssmAOP.MyLog这个注解的,就是目标类
*/
@Pointcut("@annotation(com.ssm.AOP.MyLog)")
private void MyValid() {
} @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());
}
}

  

package com.ssm.AOP;

import org.springframework.stereotype.Component;
/**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-12 18:52
*/
@Component
public class LogController { @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
public void testLogAspect() {
System.out.println("sout输出");
}
}

  

import com.ssm.model.feedback;
import com.ssm.util.PageBean;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /**
* @author xyls
* @blog name & blog address 027@0030
* @create  2019-11-15 9:52
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class SpringBaseTest {
//protected feedback feedback;
//protected PageBean pageBean; // @Before
// public void init(){
// feedback feedback=new feedback();
// }
}

  

Java自定义注解(1)的更多相关文章

  1. java自定义注解类

    一.前言 今天阅读帆哥代码的时候,看到了之前没有见过的新东西, 比如java自定义注解类,如何获取注解,如何反射内部类,this$0是什么意思? 于是乎,学习并整理了一下. 二.代码示例 import ...

  2. java自定义注解实现前后台参数校验

    2016.07.26 qq:992591601,欢迎交流 首先介绍些基本概念: Annotations(also known as metadata)provide a formalized way ...

  3. java自定义注解注解方法、类、属性等等【转】

    http://anole1982.iteye.com/blog/1450421 http://www.open-open.com/doc/view/51fe76de67214563b20b385320 ...

  4. java自定义注解知识实例及SSH框架下,拦截器中无法获得java注解属性值的问题

    一.java自定义注解相关知识 注解这东西是java语言本身就带有的功能特点,于struts,hibernate,spring这三个框架无关.使用得当特别方便.基于注解的xml文件配置方式也受到人们的 ...

  5. Java自定义注解的实现

    Java自定义注解的实现,总共三步(eg.@RandomlyThrowsException): 1.首先编写一个自定义注解@RandomlyThrowsException package com.gi ...

  6. Java自定义注解源码+原理解释(使用Java自定义注解校验bean传入参数合法性)

    Java自定义注解源码+原理解释(使用Java自定义注解校验bean传入参数合法性) 前言:由于前段时间忙于写接口,在接口中需要做很多的参数校验,本着简洁.高效的原则,便写了这个小工具供自己使用(内容 ...

  7. JAVA自定义注解 ------ Annotation

    日常开发工作中,合理的使用注解,可以简化代码编写以及使代码结构更加简单,下面记录下,JAVA自定义注解的开发过程. 定义注解声明类. 编写注解处理器(主要起作用部分). 使用注解. 相关知识点介绍, ...

  8. Java自定义注解和运行时靠反射获取注解

    转载:http://blog.csdn.net/bao19901210/article/details/17201173/ java自定义注解 Java注解是附加在代码中的一些元信息,用于一些工具在编 ...

  9. JAVA自定义注解

    在学习使用Spring和MyBatis框架的时候,使用了很多的注解来标注Bean或者数据访问层参数,那么JAVA的注解到底是个东西,作用是什么,又怎样自定义注解呢?这篇文章,即将作出简单易懂的解释. ...

  10. Java 自定义注解

    在spring的应用中,经常使用注解进行开发,这样有利于加快开发的速度. 介绍一下自定义注解: 首先,自定义注解要新建一个@interface,这个是一个注解的接口,在此接口上有这样几个注解: @Do ...

随机推荐

  1. ASP.NET MVC5基础 – MVC文件架构

    创建MVC项目 首先,我们使用Visual Studio2019创建一个MVC架构的应用程序.步骤如下:首先打开VS2019,在启动页选择[创建新项目].然后选择创建 ASP.NET Web 应用程序 ...

  2. Python实现一个键对应多个值的字典(multidict)

    一个字典就是一个键对应一个单值的映射.如果你想要一个键映射多个值,那么你就需要将这多个值放到另外的容器中, 比如列表或者集合里面.比如,你可以像下面这样构造这样的字典: d = { 'a' : [1, ...

  3. Java并发专题

    ——参考于码农求职小助手公众号 1.并行和并发有什么区别? 1. 并行是指两个或者多个事件在同一时刻发生:而并发是指两个或多个事件在同一时间间隔发生: 2. 并行是在不同实体上的多个事件,并发是在同一 ...

  4. Ext.ux.UploadDialog上传大文件 HTTP 错误 413.1 - Request Entity Too Large Web 服务器拒绝为请求提供服务,因为该请求实体过大。Web 服务器无法为请求提供服务,因为它正尝试与客户证书进行协商,但请求实体过大。

    问题描述 问题:HTTP 错误 404.13 - Not Found 请求筛选模块被配置为拒绝超过请求内容长度的请求. 原因:Web 服务器上的请求筛选被配置为拒绝该请求,因为内容长度超过配置的值(I ...

  5. 【Angular】学习笔记-环境部署、项目建立相关

    Angular官网>搭建环境 首先要安装Node.js.官网>Download 一直next就好了. 安装node.js的目的是使用npm这些命令啦 然后这里推荐下载使用git SCM 也 ...

  6. 三大免费开源的php语言cms系统 用好它们让你一天建好一个网站

    php语言只所以在web开发领域占据半壁江山,是因为它有太多的生态,成熟的框架体系,广泛的开源cms系统.建设网站的时候,都想提升开发效率,效率就是成本,如果你用原生php语言开发一个项目,既要设计数 ...

  7. Mac版Sourcetree的安装使用

    本人也在亲测,感觉很有效,和大家分享,参考链接: https://www.jianshu.com/p/b8d0547a8449

  8. Android 亮度调节功能开发思路整理

    做 Android 音视频播放器开发的时候,我们基本都会遇到一类需求:音量 & 亮度 调节.其中做亮度调节功能的时候,发现还是有一定复杂度的. Android亮度调节分为两个类,分别是: An ...

  9. QT--HTTP图片下载器

    QT--HTTP图片下载器 1.http使用前提 QT       += core gui network    //必须加上network 2.必须头文件 #include <QNetwork ...

  10. 更改 undo_retention 时,Lob retention 不更改 (Doc ID 563470.1)

    Lob retention not changing when undo_retention is changed (Doc ID 563470.1) APPLIES TO: Oracle Datab ...