有些时候我们需要一个类中的所有属性信息,在类属性少的情况下我们可以一个一个的通过get和set获得,但是如果多了的话就比较麻烦了,在这里我们可以通过反射来遍历。
public void getAlixIntegrity(ApplyCust applyCust) throws NoSuchMethodException, Exception{ // 获取实体类的所有属性,返回Field数组 Field[] field = applyCust.getClass().getDeclaredFields(); // 遍历所有属性 for (int j = 0; j < field.length; j++) { // 获取属性的名字 String name = field[j].getName(); // 将属性的首字符大写,方便构造get,set方法 name = name.substring(0, 1).toUpperCase() + name.substring(1); // 获取属性的类型 String type = field[j].getGenericType().toString(); // 如果type是类类型,则前面包含"class ",后面跟类名 //System.out.PRintln("属性为:" + name); if (type.equals("class java.lang.String")) { Method m = applyCust.getClass().getMethod("get" + name); // 调用getter方法获取属性值 String value = (String) m.invoke(applyCust); //System.out.println("数据类型为:String"); if (value != null || value == "") { //System.out.println("属性值为:" + value); } else { //System.out.println("属性值为:空"); nullCount ++; } } if (type.equals("class java.lang.Integer")) { Method m = applyCust.getClass().getMethod("get" + name); Integer value = (Integer) m.invoke(applyCust); //System.out.println("数据类型为:Integer"); if (value != null) { //System.out.println("属性值为:" + value); } else { //System.out.println("属性值为:空"); nullCount ++; } } if (type.equals("class java.lang.Long")) { Method m = applyCust.getClass().getMethod("get" + name); Long value = (Long) m.invoke(applyCust); //System.out.println("数据类型为:Long"); if (value != null) { //System.out.println("属性值为:" + value); } else { //System.out.println("属性值为:空"); nullCount ++; } } if (type.equals("class java.lang.Double")) { Method m = applyCust.getClass().getMethod("get" + name); Double value = (Double) m.invoke(applyCust); //System.out.println("数据类型为:Double"); if (value != null) { //System.out.println("属性值为:" + value); } else { //System.out.println("属性值为:空"); nullCount ++; } } if (type.equals("class java.util.Date")) { Method m = applyCust.getClass().getMethod("get" + name); Date value = (Date) m.invoke(applyCust); //System.out.println("数据类型为:Date"); if (value != null) { //System.out.println("属性值为:" + value); } else { //System.out.println("属性值为:空"); nullCount ++; } } } tatolCount = field.length; integrity = (tatolCount - nullCount) * 1.0 / tatolCount; return integrity; } 这样有什么类型就都可以遍历了。
新闻热点
疑难解答