一:为何使用注解java
在项目开发中,参数的校验是不可避免的,一般状况下,咱们会使用if条件判断,若是ide
前台传递不少参数过来,那么须要写不少累赘的if代码来校验参数,而使用注解能够避免测试
这个问题,注解须要依赖javaBean,在字段上咱们能够绑定一些元数据,而后在校验的ui
使用使用,下面是一个简单的实例:this
自定义注解:NotNull对象
package com.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * */ /** * @author Administrator * 校验非空字段 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface NotNull { String value(); }
javaBean:Person,在字段上面咱们能够绑定一些元数据blog
/** * */ package com.hlcui.entity; import com.annotation.NotNull; /** * @author Administrator * */ public class Person { @NotNull(value="身份证号不能为空") private String id; @NotNull(value="姓名不能为空") private String name; private String salary; private String mgr; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } public String getMgr() { return mgr; } public void setMgr(String mgr) { this.mgr = mgr; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", salary=" + salary + ", mgr=" + mgr + "]"; } }
自定义异常类:ip
/** * */ package com.hlcui.exception; /** * @author Administrator * */ public class CustBusinessException extends RuntimeException{ /** * */ private static final long serialVersionUID = 1L; public CustBusinessException() { } public CustBusinessException(String s) { super(s); } public CustBusinessException(String s, Throwable throwable) { super(s, throwable); } public CustBusinessException(Throwable throwable) { super(throwable); } }
咱们还须要一个注解解析器,也能够叫作控制器,一般是经过反射获得注解信息:开发
/** * */ package com.hlcui.util; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import com.annotation.NotNull; import com.hlcui.exception.CustBusinessException; /** * @author Administrator * */ public class CommonUtils { /** * 经过反射来获取javaBean上的注解信息,判断属性值信息,而后经过注解元数据 * 来返回 * @param t */ public static <T> void doValidator(T t){ Class<?> clazz = t.getClass(); Field[] fields = clazz.getDeclaredFields(); for(Field field:fields){ NotNull notNull = field.getDeclaredAnnotation(NotNull.class); if(null!=notNull){ Object value = getValue(t,field.getName()); if(!notNull(value)){ throwExcpetion(notNull.value()); } } } } public static <T> Object getValue(T t,String fieldName){ Object value = null; try { BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass()); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor property:props){ if(fieldName.equals(property.getName())){ Method method = property.getReadMethod(); value = method.invoke(t,new Object[]{}); } } } catch (Exception e) { e.printStackTrace(); } return value; } public static boolean notNull(Object value){ if(null==value){ return false; } if(value instanceof String && isEmpty((String)value)){ return false; } if(value instanceof List && isEmpty((List<?>)value)){ return false; } return null!=value; } public static boolean isEmpty(String str){ return null==str || str.isEmpty(); } public static boolean isEmpty(List<?> list){ return null==list || list.isEmpty(); } public static void throwExcpetion(String msg){ if(null!=msg){ throw new CustBusinessException(msg); } } public static void handlerExcpetion(Exception e){ if(e instanceof CustBusinessException){ System.out.println(((CustBusinessException)e).getMessage()); }else{ System.out.println("调用失败"); } } }
而后咱们能够测试校验状况:get
/** * */ package com.hlcui.test; import org.junit.Test; import com.hlcui.entity.Person; import com.hlcui.util.CommonUtils; /** * @author Administrator * */ public class TestAnnotation { @Test public void testNotNull() { try { Person person = new Person(); person.setId("1"); person.setName("李白"); CommonUtils.doValidator(person); } catch (Exception e) { CommonUtils.handlerExcpetion(e); } } }
首先把
person.setId("1");
这行注释掉,运行结果会怎样呢?
身份证号不能为空
校验成功!
下面将比较重要的代码作一下讲解:
1:
public static <T> void doValidator(T t){ Class<?> clazz = t.getClass(); Field[] fields = clazz.getDeclaredFields(); for(Field field:fields){ NotNull notNull = field.getDeclaredAnnotation(NotNull.class); if(null!=notNull){ Object value = getValue(t,field.getName()); if(!notNull(value)){ throwExcpetion(notNull.value()); } } } }
首先形参为一个实体对象,这里是使用泛型,而后经过getClass()方法,获取该对象的字节码对象Class,
进而获得全部的字段,而后遍历字段,获取每一个字段上面的注解,若是没有注解,则为null,说明不须要校验
,若是不为null,则获取该字段的值,而后判断是否为空(包括null或者""),若是是则抛出异常。
2:
public static <T> Object getValue(T t,String fieldName){ Object value = null; try { BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass()); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor property:props){ if(fieldName.equals(property.getName())){ Method method = property.getReadMethod(); value = method.invoke(t,new Object[]{}); } } } catch (Exception e) { e.printStackTrace(); } return value; }
这里面用到了内省(反射中专门针对javaBean),根据该类的字节码文件获取Beaninfo对象,顾名思义就是
包含bean信息的一个对象,而后获取每个字段的描述器,经过描述器能够获取每一个字段的名称、set方法、get
方法,能够获取字段的值,也能够set对象的值,很方便。
固然还可使用拼接的方式,接set+字段,来获得set方法,和get方法。