廖雪峰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实例包 ...
随机推荐
- hashCode()方法 和 hash()方法
String str = "abc"; String str1 = "abc"; System.out.println(str == str1); //true ...
- yield return:使用.NET的状态机生成器
通过关键字词组yield return,.Net Framework(从2.0开始)会为我们生成一个状态机.状态机实际上就是一个可枚举的类型化集合 理解yield return的工作方式 关键字词组y ...
- Unity 5 Game Optimization (Chris Dickinson 著)
1. Detecting Performance Issues 2. Scripting Strategies 3. The Benefits of Batching 4. Kickstart You ...
- out, ref 和 params 的区别和用法
1. out 参数. 如果你在一个方法中,返回多个相同类型的值,可以考虑返回一个数组. 但是,如果返回多个不同类型的值,返回数组就不可取.这个时候可以考虑使用out参数. out参数就侧重于在一个方法 ...
- SpringBoot2
2018.3月Spring Boot2.0发布,是Spring Boot1.0发布4年之后第一次重大修订.Spring Boot2.0版本经历了 17 个月的开发,有 215 个不同的使用者提供了超过 ...
- C# string 转 bool
bool _b = Convert.ToBoolean("False"); "_b => false" // // 摘要: // 将逻辑值的指定字 ...
- 使用apache cxf实现webservice服务
1.在idea中使用maven新建web工程并引入spring mvc,具体可以参考https://www.cnblogs.com/laoxia/p/9311442.html; 2.在工程POM文件中 ...
- 学习concurrency programming进展
看了一段时间的actor model,goroutine之类的东东,最近在github上写了个简单的框架, 注:未做大量测试,仅供学习用,勿用于生产用途 链接: https://github.com/ ...
- nginx 镜像使用说明
nginx 镜像说明 目录 说明 /etc/nginx nginx安装目录 /usr/share/nginx/html nginx网站资源存放的目录 运行nginx容器,相关命令: 命令 说明 doc ...
- Centos中iptables和firewall防火墙开启、关闭、查看状态、基本设置等(转)
iptables防火墙 1.基本操作 # 查看防火墙状态 service iptables status # 停止防火墙 service iptables stop # 启动防火墙 servi ...