廖雪峰Java4反射与泛型-2注解-3处理注解
1.处理注解
- 注解本身对对代码逻辑没有任何影响
- SOURCE类型的注解在编译期就被丢掉了
- CLASS类型的注解仅保存在class文件中
- RUNTIME类型的注解在运行期可以被读取
- 如何使用注解由工具决定
因此如何处理注解只针对RUNTIME类型的注解
如何读取RUNTIME类型的注解
思路:
- Annotation也是class
- 所有Annotation继承自java.lang.annotation.Annotation
- 使用反射API,就可以获取
2.使用反射API读取Annotation
Report.java
package com.reflection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Report {
int type() default 0;
String level() default "info";
String value() default "";
}
Person.java
package com.reflection;
@Report(type=1,level = "error")
public class Person {
}
- 方法1: 判断某个Annotation是否存在,存在再打印注解的信息
- Class.isAnnotationPresent(Class)
- Field.isAnnotationPresent(Class)
- Method.isAnnotationPresent(Class)
- Constructor.isAnnotationPresent(Class)
package com.reflection;
public class Main {
public static void main(String[] args){
Class cls = Person.class;
if (cls.isAnnotationPresent(Report.class)){
Report report = (Report) cls.getAnnotation(Report.class);
int type = report.type();
String level = report.level();
System.out.println(type+"\t"+level);
}
}
}
- 方法2:获取某个Annotation,注解对象不为空,再打印注解的信息
* Class.getAnnotation(Class)
* Field.getAnnotation(Class)
* Method.getAnnotation(Class)
* Constructor.getAnnotation(Class)
* getParameterAnnotations()
package com.reflection;
public class Main {
public static void main(String[] args){
Class cls = Person.class;
Report report = (Report) cls.getAnnotation(Report.class);
if (report != null){
int type = report.type();
String level = report.level();
System.out.println(type+ "\t" + level);
}
}
}

3.读取方法参数的Annotation:
NotNull.java
package com.reflection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface NotNull{
}
Range.java
package com.reflection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Range{
int min() default 1;
int max() default 100;
}
Hello.java
package com.reflection;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class Hello {
public String hello(@NotNull String name,@NotNull @Range(max = 5) int age){
return name+"\t"+age;
}
}
TestHello.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class TestHello {
public static void main(String[] args) throws Exception{
Class cls = Hello.class;
Method m = cls.getMethod("hello", String.class, int.class);
//方法的参数本身可以看作是一个数组,每一个参数又可以定义多个注解。因此一次获取所有方法的注解,要用2维数组来表示
Annotation[][] annos = m.getParameterAnnotations();
Parameter[] params = m.getParameters();
for(int i=0;i<annos.length;i++){
System.out.print(params[i]+"\t{");
for(Annotation anno:annos[i]){
System.out.print(anno.toString()+"\t");
}
System.out.print("}");
System.out.println();
}
}
}

4.读取字段的Annotation
NotNull.java
package com.reflection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NotNull{
}
Range.java
package com.reflection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Range{
int min() default 1;
int max() default 100;
}
Person.java
package com.reflection;
public class Person{
@NotNull
public String name;
@Range(max=20)
public int age;
public Person(String name,int age){
this.name=name;
this.age = age;
}
}
Main.java
package com.reflection;
//Java注解本身对代码逻辑并不产生任何影响,所以应用的这些注解并不会自动对name和age进行检查,我们需要自己的代码应用这些注解
import java.lang.reflect.Field;
public class Main{
public static void main(String[] args) throws Exception{
Person p1 = new Person("xiaoming",25);
Person p2 = new Person(null,15);
checkPerson(p1);
checkPerson(p2);
}
static void checkPerson(Person p) throws Exception{
System.out.println("check " +p + "...");
Class cls = Person.class;
for(Field f:cls.getFields()){
checkField(f,p);
}
}
static void checkField(Field f,Person p) throws Exception{
if (f.isAnnotationPresent(NotNull.class)){
Object r = f.get(p);
if (r==null){
System.out.println("Error Field " + f.getName() + "is null...");
}
}
if (f.isAnnotationPresent(Range.class)){
Range range = f.getAnnotation(Range.class);
int n = (Integer) f.get(p);//参见反射2field
if(n < range.min() || n > range.max()){
System.out.println("Error Field " + f.getName()+ "is out of range...");
}
}
}
}

5.总结:
- 可以在运行期通过反射读取RUNTIME类型的注解,不要漏写@Retention(RetentionPolicy.RUNTIME)
- 可以通过工具处理注解来实现相应的功能
* 对JavaBean的属性值按规则进行检查
* JUnit会自动运行@Test注解的测试方法
请根据注解:
- @NotNull检查该属性为非null
- @Range检查整形介于minmax,或者检查字符串长度介于minmax
- @ZipCode: 检查字符串是否全部由数字构成,且长度恰好为value
实现对Java Bean的属性值检查。如果检查为通过,抛出异常
廖雪峰Java4反射与泛型-2注解-3处理注解的更多相关文章
- 廖雪峰Java4反射与泛型-2注解-2定义注解
1.定义注解 使用@interface定义注解Annotation 注解的参数类似无参数方法 可以设定一个默认值(推荐) 把最常用的参数命名为value(推荐) 2.元注解 2.1Target使用方式 ...
- 廖雪峰Java4反射与泛型-2注解-1使用注解
1.Annotation定义 注解是放在Java源码的类.方法.字段.参数前的一种标签.如下 package com.reflection; import org.apache.logging.log ...
- 廖雪峰Java4反射与泛型-3泛型-7泛型和反射
1.部分反射API是泛型 1.1获取反射API的泛型 部分反射API是泛型,如Class<T>是泛型 //如果使用Class,不带泛型,出现compile warning编译警告 Clas ...
- 廖雪峰Java4反射与泛型-3范型-4擦拭法
1.擦拭法是Java泛型的实现方式. 编译器把类型视为Object. * 泛型代码编译的时候,编译器实际上把所有的泛型类型T统一视为Object类型.换句话说,虚拟机对泛型一无所知,所有的工作都是编译 ...
- 廖雪峰Java4反射与泛型-3范型-6super通配符
1.super通配符 1.1super通配符第一种用法 泛型的继承关系 Pair<Integer>不是Pair<Number>的子类,如 static void set(Pai ...
- 廖雪峰Java4反射与泛型-3范型-5extends通配符
1.泛型的继承关系: Pair<Integer>不是Pair<Number>的子类 add()不接受Pair<Integer> Pair.java package ...
- 廖雪峰Java4反射与泛型-3范型-3编写泛型
编写泛型类比普通的类要麻烦,而且很少编写泛型类. 1.编写一个泛型类: 按照某种类型(例如String)编写类 标记所有的特定类型例如String 把特定类型替换为T,并申明 Pair.java pa ...
- 廖雪峰Java4反射与泛型-1反射-2访问字段Field和3调用方法Method
2.字段Field 2.1.通过Class实例获取字段field信息: getField(name): 获取某个public的field,包括父类 getDeclaredField(name): 获取 ...
- 廖雪峰Java4反射与泛型-1反射-1Class类
1.Class类与反射定义 Class类本身是一种数据类型(Type),class/interface的数据类型是Class,JVM为每个加载的class创建了唯一的Class实例. Class实例包 ...
随机推荐
- odoo软件名称及授权协议的变化
先看一张表格 起步时叫TinyERP,微小的ERP:发展中期叫做OpenERP,开放的ERP:历经10年积累的软件,客户群,开发支持用户群,开始构筑自己的商业模式.到8版本,改名为Odoo.同时,软件 ...
- (4)django的新手三件套(返回页面、返回字符、重定向)
from django.shortcuts import render,HttpResponse,redirect 新手三件套,前期开发都会用到 render #向浏览器返回页面 HttpResp ...
- git使用之放弃本地修改
一,未使用 git add 缓存代码时. 可以使用 git checkout -- filepathname (比如: git checkout -- readme.md ,不要忘记中间的 “-- ...
- JPI中常使用的类介绍:
Math类: java.lang包下的 final,不可被继承, 其中的方法和属性都是静态的 其构造方法私有化了,其他类不可以使用构造方法. 向上取整:Math.ceil(double d); 向下取 ...
- 内置函数——filter和map
filter filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False , filter()根据判断结果自动过滤掉不符合条件的元 ...
- 学习笔记:Javascript 变量 包装对象
学习笔记:Javascript 变量 包装对象 如下代码,可以输出字符的长度. var str = "Tony"; str.length; 这时再试试以下代码,返回是 undefi ...
- 笔记:Python 默认参数必须指向不变对象
笔记:Python 默认参数必须指向不变对象 学习记录 >>> def add_end(L=[]): L.append('END') return L >>> ad ...
- zabbix--3.0--3
使用JMX监控jvm vim /usr/local/tomcat/bin/catalina.sh 添加如下内容 CATALINA_OPTS="$CATALINA_OPTS -Dcom ...
- Android Monkey测试入门
第一步:搭建环境:主要是安装和搭建java和sdk环境,说白了,对我们安卓开发来说,只要搭建好了Android开发环境,Monkey测试环境基本就是OK的了.可以参考:http://www.cnblo ...
- MySQL 检索数据(SELECT)
检索单个列 mysql> SELECT 列名 FROM 表名; 如下,从表products中检索prod_name列 mysql> SELECT prod_name FROM ...