java annotation使用介绍
还望支持个人博客站:http://www.enjoytoday.cn
介绍
Annotation的中文名字叫注解,开始与JDK 1.5,为了增强xml元数据和代码的耦合性的产物。注解本身并没有业务逻辑处理,仅仅是一个声明,具体的处理需要交由使用这些注解的工具类或方法,原则上来说,注解应该是对代码书写的一个辅助,即注解是否存在均不能影响代码的正常运行。现在java中使用注解的场景是越来越多,如orm框架,Ioc框架等,开发人员使用注解的方式可以简化对于元数据的维护和构建(xml配置数据),接下来主要介绍自定义注解的方法和如何使用自定义注解。
自定义注解
和注解相关的java文件的位置在java.lang.annotation包下自定义注解比较简单 格式和一般的java文件类似,声明如下:
@Documented
@Target(ElementType.TYPE)
@Retentiion(RetentionPolicy.RUNTIME)
@Inherited
public @interface annotation{
int value() default -1;
}
如上所示就是一般注解定义的格式,其中在声明注解之前需要定义注解的使用场景等信息,即添加元注解,java提供的元注解有四类,介绍如下:
1)@Documented
一个简单的问但包含注解,添加即代表注解包含在Javadoc中,我们可以通过javadoc -d doc *.java生成一个java的doc文档。
2)@Target
声明注解的使用场景,默认为可用于任何场景,参数类型为枚举,包括的属性有如下:
- ElementType.TYPE:在class,interface(包括@interface),enum声明前
- ElementType.FIELD:全局变量前
- ElementType.METHOD:方法前
- ElementType.PARAMETER:方法参数前
- ElementType.CONSTRUCTOR:构造方法前
- ElementType.LOCAL_VARIABLE:方法内部参数前
- ElementType.ANNOTATION_TYPE:@interface前
- ElementType.PACKAGE:用于记录java文件的package信息
**3)@Retention**
定义该注解的生命周期,参数类型如下:
- RetentionPolicy.SOURCE:编译器要丢弃的注释。
- RetentionPolicy.CLASS: 编译器将把注释记录在类文件中,但在运行时 VM 不需要保留注释。默认为该属性
- RetentionPolicy.RUNTIME:编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。
**4)@Inherited**
该注解表明子类继承该注解,反之不继承。
## 使用
使用分三段介绍:首先给出注解的定义,然后给出注解的使用方式,最后给出注解的逻辑处理方法。
### 自定义一个注解
注解的自定义声明为@interface默认继承Annotation接口,格式如下:
/**
* @date 17-2-8.
* @className ClassTypeModel
* @serial 1.0.0
* @see Target @Target:设置注释引用的类型
* @see ElementType 注释引用类型枚举 ElementType.TYPE:class interface(包括annotation),enum引用
* @see Retention @Retention:注释适用范围
* @see RetentionPolicy 注释使用类型枚举
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@AnnotationTypeModel
public @interface TypeModel {
String value() default "TypeModel";
int id() default -7;
boolean isActive() default false;
int value () default -1;
}
如上,注解中的方法的返回可以通过 default 设置默认返回值。
注解的引用
注解的使用需要根据注解已经声明的使用场景中使用,否则会包类型不匹配错误,使用如下:
@TypeModel(id = 7, isActive = true,value = "MyClass")
public class MyClass {
@ConstructorTypeModel(id = 1000,isActive = true,value = "MyClass")
public MyClass(){
System.out.print("this is MyClass ConstructorTypeModel\n");
annotatioinTestMethod(true);
}
@FieldTypeModel(id = 10,isActive = true,value = "type")
private String type;
@FieldTypeModel(id = 11,isActive = true,value = "name")
private String name;
@FieldTypeModel(id = 10,isActive = true,value = "favorite")
private String favorite;
@MethodTypeModel(id = 5,isActive = true,value = "annotatioinTestMethod")
private void annotatioinTestMethod(@ParamTypeModel(id = 6,isActive = true,value = "testparam") boolean isTest){
@LocalVarTypeModel(isActive = true)
boolean flag=isTest;
System.out.print("this is annotationTestMethod.\n");
}
......
}
注解的处理
注解在使用后我们可以通过java反射的原理获取到注解的值,方便从而方便我们之后的业务逻辑处理,处理如下:
/**
* 通过反射获取注入的内容
*/
private static void reflectAnnotations(){
MyClass myClass=new MyClass();
// //only jdk over 1.8
// MyClass myClass1=new @UseTypeModel(isActive = true) MyClass();
Class<?> tClass=myClass.getClass();
Annotation[] annotations= tClass.getDeclaredAnnotations();
annotationPrint(annotations,"classAnnotations");
Constructor<?>[] constructors= tClass.getDeclaredConstructors();
System.err.println("Constructor of all.\n");
for (Constructor<?> constructor:constructors){
Annotation[] constructorDeclaredAnnotations= constructor.getDeclaredAnnotations();
annotationPrint(constructorDeclaredAnnotations,"constructorDeclaredAnnotations");
}
System.err.println("Methods of all.\n");
Method[] methods=tClass.getDeclaredMethods();
for (Method method:methods){
Annotation[] methodAnnotation=method.getDeclaredAnnotations();
annotationPrint(methodAnnotation,"methodAnnotation");
Annotation[][] paramAnnotations= method.getParameterAnnotations();
for (Annotation[] annotation: paramAnnotations){
annotationPrint(annotation,"paramAnnotations");
}
}
System.err.println("Field of all.\n");
Field[] fields=tClass.getDeclaredFields();
for (Field field:fields){
Annotation[] filedAnnotations= field.getDeclaredAnnotations();
annotationPrint(filedAnnotations,"filedAnnotations");
}
}
private static void annotationPrint(Annotation[] annotations,String type){
for (Annotation annotation: annotations){
System.out.println(type+" toString:"+annotation.toString()+"\n");
Class<?> clazz= annotation.annotationType();
System.out.println("annotation class name:"+clazz.getName());
Annotation[] declaredAnnotations= clazz.getDeclaredAnnotations();
//注释的注释
for (Annotation annotation1:declaredAnnotations){
System.out.println(annotation.getClass().getSimpleName()+" annotation toString:"+annotation1.toString()+"\n");
}
}
}
如上就是一个简单的注解demo介绍.
源码
源码下载地址:annotationdemojava
java annotation使用介绍的更多相关文章
- Java Annotation认知(包括框架图、详细介绍、示例说明)
摘要 Java Annotation是JDK5.0引入的一种注释机制. 网上很多关于Java Annotation的文章,看得人眼花缭乱.Java Annotation本来很简单的,结果说的人没说清楚 ...
- Java Annotation认知(包括框架图、详细介绍、示例说明)(转)
本文转自:http://www.cnblogs.com/skywang12345/p/3344137.html 网上很多关于Java Annotation的文章,看得人眼花缭乱.Java Annota ...
- paip.Java Annotation注解的作用and 使用
paip.Java Annotation注解的作用and 使用 作者Attilax 艾龙, EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog. ...
- Java Annotation原理分析(一)
转自:http://blog.csdn.net/blueheart20/article/details/18725801 小引: 在当下的Java语言层面上,Annotation已经被应用到了语言的各 ...
- Java Annotation 及几个常用开源项目注解原理简析
PDF 版: Java Annotation.pdf, PPT 版:Java Annotation.pptx, Keynote 版:Java Annotation.key 一.Annotation 示 ...
- Java Annotation 机制源码分析与使用
1 Annotation 1.1 Annotation 概念及作用 1. 概念 An annotation is a form of metadata, that can be added ...
- Java Annotation手册
Java Annotation手册 作者:cleverpig(作者的Blog:http://blog.matrix.org.cn/page/cleverpig) 原文:http://www.matri ...
- 【转】Spring学习---Bean配置的三种方式(XML、注解、Java类)介绍与对比
[原文]https://www.toutiao.com/i6594205115605844493/ Spring学习Bean配置的三种方式(XML.注解.Java类)介绍与对比 本文将详细介绍Spri ...
- 1.2.4 Java Annotation 提要
(本文是介绍依赖注入容器Spring和分析JUnit源码的准备知识) Java Annotation(标注) java.lang.annotation.Annotation是全部Java标注的父接口. ...
随机推荐
- Linux下使用 github+hexo 搭建个人博客06-next主题接入数据统计
之前说了 next 主题的优化和接入评论系统.让我们完成了自己所需的页面风格和排版,也可让访问用户在每篇博文评论,完成博主和访问用户的交互. 本章我们继续讲解其他重要功能. 既然是一个网站,那么我们就 ...
- Linux日志中出现大量dhclient mesage浅析
最近检查发现一台Linux服务器,发现其日志里面有大量下面信息,其中部分信息做了脱敏处理.其中一个地址A(192.168.AAA.AAA) 为DNS服务器地址,地址B(192.168.BBB.BBB) ...
- python3.7安装, 解决pip is configured with locations that require TLS/SSL问题
python3.7安装, 解决pip is configured with locations that require TLS/SSL问题1.安装相关依赖 yum install gcc libff ...
- linux 性能调优工具参考 (linux performance tools)
之前发现几张图对于linux使用者有着较强的参考意义,下面对其进行简单备忘: # linux 静态信息查看工具 # linux 性能测试工具 benchmark # linux 性能观测工具 # li ...
- Shell—常见报错问题
bash:$'\r': command not found 造成这个问题的原因是Windows环境下换行的“\r”到了Linux环境下不能够识别了,因为Linux环境下默认的换行符为“\n”,我们只需 ...
- TensorFlow从1到2(十三)图片风格迁移
风格迁移 <从锅炉工到AI专家(8)>中我们介绍了一个"图片风格迁移"的例子.因为所引用的作品中使用了TensorFlow 1.x的代码,算法也相对复杂,所以文中没有仔 ...
- React 组件传值 父传递儿子
10===> 传递参数 import React from "react" //一定要导入React // 函数类型去创建组件 export function Web1(pr ...
- MongoDB学习笔记(三、MongoDB聚合与更新)
目录: 聚合 更新 更新选择器 ObjectId 更新操作的原子性 聚合: 聚合语法:db.collectionName.aggregate(aggregate_operation) 聚合操作其实就是 ...
- luoguP3649 [APIO2014]回文串
题意 关于回文自动机的讲解见这里 由于回文串个数是\(O(n)\)的,直接回文自动机上统计并比较即可. code: #include<bits/stdc++.h> using namesp ...
- 第04组 Beta冲刺(3/5)
队名:new game 组长博客 作业博客 组员情况 鲍子涵(队长) 过去两天完成了哪些任务 整理素材 接下来的计划 素材和脚本相连 引入声音素材 还剩下哪些任务 让游戏本体运行 遇到了哪些困难 时间 ...