java反射机制实践—对象属性预处理
引言
最近碰到了个问题,数据从前端传入之后需要进行校验。于是乎就简单的用get,set方法,但这样就使代码看起来异常臃肿,不美观。
未引入反射之前的代码
if(pa.getLitigationAmount().length()>15)
{
pa.setLitigationAmount(RoundNoOfUtil.RoundNoOf(pa.getLitigationAmount(),2));
}
if(pa.getCalculatedPaidInterest().length()>15)
{
pa.setCalculatedPaidInterest(RoundNoOfUtil.RoundNoOf(pa.getCalculatedPaidInterest(),2));
}
if(pa.getDeclaredFee().length()>15)
{
pa.setDeclaredFee(RoundNoOfUtil.RoundNoOf(pa.getDeclaredFee(),2));
}
if(pa.getExecuteFee().length()>15)
{
pa.setExecuteFee(RoundNoOfUtil.RoundNoOf(pa.getExecuteFee(),2));
}
if(pa.getExecuteAll().length()>15)
{
pa.setExecuteAll(RoundNoOfUtil.RoundNoOf(pa.getExecuteAll(),2));
}
if(pa.getExecuteAmount().length()>15)
{
pa.setExecuteAmount(RoundNoOfUtil.RoundNoOf(pa.getExecuteAmount(),2));
}
if(pa.getExecuteNum().length()>15)
{
pa.setExecuteNum(RoundNoOfUtil.RoundNoOf(pa.getExecuteNum(),2));
}
if(pa.getFee().length()>15)
{
pa.setFee(RoundNoOfUtil.RoundNoOf(pa.getFee(),2));
}
if(pa.getHalfLitigationFee().length()>15)
{
pa.setHalfLitigationFee(RoundNoOfUtil.RoundNoOf(pa.getFee(),2));
}
if(pa.getLawyerFee().length()>15)
{
pa.setLawyerFee(RoundNoOfUtil.RoundNoOf(pa.getLawyerFee(),2));
}
if(pa.getLitigationFee().length()>15)
{
pa.setLitigationFee(RoundNoOfUtil.RoundNoOf(pa.getLitigationFee(),2));
}
if(pa.getLitigationInterest().length()>15)
{
pa.setLitigationInterest(RoundNoOfUtil.RoundNoOf(pa.getLitigationInterest(),2));
}
if(pa.getLitigationPrincipal().length()>15)
{
pa.setLitigationPrincipal(RoundNoOfUtil.RoundNoOf(pa.getLitigationPrincipal(),2));
}
if(pa.getLoanNum().length()>15)
{
pa.setLoanNum(RoundNoOfUtil.RoundNoOf(pa.getLoanNum(),2));
}
if(pa.getRateMonth().length()>15)
{
pa.setRateMonth(RoundNoOfUtil.RoundNoOf(pa.getLoanNum(),2));
}
if(pa.getRateYear().length()>15)
{
pa.setRateYear(RoundNoOfUtil.RoundNoOf(pa.getRateYear(),2));
}
if(pa.getPaidInterest().length()>15)
{
pa.setPaidInterest(RoundNoOfUtil.RoundNoOf(pa.getPaidInterest(),2));
}
if(pa.getPaidPrincipal().length()>15)
{
pa.setPaidPrincipal(RoundNoOfUtil.RoundNoOf(pa.getPaidPrincipal(),2));
}
if(pa.getSecurityFee().length()>15)
{
pa.setSecurityFee(RoundNoOfUtil.RoundNoOf(pa.getSecurityFee(),2));
}
一堆if判断,看起来傻乎乎的。由于都是对对象属性进行操作,因此想到了用反射来解决。
引入反射后的代码
Class cls = pa.getClass();
//获取所有属性列表
Field[] fields = cls.getDeclaredFields();
for (Field field:fields)
{
//开启私有化成员权限,private属性默认权限为false.从这可以看出private只是逻辑上的私有化,实际上通过反射机制依然可以获取到值。
field.setAccessible(true);
//获取数量类型 如 String Integer
String type_name = field.getType().getSimpleName();
if("String".equals(type_name))
{
//开始对String类型的属性进行处理
String str = (String) field.get(pa);
// 初步校验
if(str!=null&&str.length()>15&&(str.contains("99999")|str.contains("00000")))
{
//操作
str = RoundNoOfUtil.RoundNoOf(str,2);
}
field.set(pa,str);
}
if("Date".equals(type_name))
{
//同上
Date date = (Date)field.get(pa);
if(date==null)
{
field.set(pa,new Date(2000,4,20));
}
}
}