这篇文章主要介绍Java中如何使用反射对负数进行排查,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
1. 很久没有写反射了,好多方法忘记了下面一个对负数的检查列子,不是很好,凑活用吧
public class NumberUtil {
/**
* 返回对象属性,对象属性为double 不能为负数,为负数会提醒
*@Title:checkNumFilter
*@Description:TODO
* @Param:@param obj
* @Param:@return
*@return :boolean
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*@throws
*@author :kuchawyz2019年10月10日
*/
public static boolean checkNumFilter(Object obj)
throws NoSuchMethodException,
SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
if(obj != null){
Class<?> clz = obj.getClass();
Field[] filds = clz.getDeclaredFields();
for(Field field :filds){
if(field.getGenericType().toString().equals("double")){
String methodName = "get"+upperCase(field.getName());
Method m = obj.getClass().getDeclaredMethod(methodName);
double val = (double) m.invoke(obj);
if(val < 0){
throw new ErrorFormateException("你传入的数字有负数的");
}
}
}
return true;
}
return false;
}
/**
* 对给定的字符串首字母变成大写
* (这里先将字符串转为字符数组,
* 然后将数组的第一个元素,即字符串首字母,进行ASCII 码前移,
* ASCII 中大写字母从65开始,小写字母从97开始,所以这里减去32)
*@Title:upperCase
*@Description:TODO
* @Param:@param str
* @Param:@return
*@return :String
*@throws
*@author :kuchawyz2019年10月10日
*/
public static String upperCase(String str) {
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}
}
以上是“Java中如何使用反射对负数进行排查”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注天达云行业资讯频道!