packagecn.ucmed.pangu.lib; importlombok.extern.slf4j.Slf4j; importjava.lang.reflect.Field; importjava.util.ArrayList; importjava.util.Arrays; importjava.util.List; @Slf4j public classReflectionUtil { /** * 根据属性名查找对应的属性,子类没有的属性会到父类找 * * @paramo * @paramfieldName * @return */ public staticField getDeclareField(Object o, String fieldName) { Field field = null; Class<?> clazz =o.getClass(); for (; clazz != Object.class; clazz =clazz.getSuperclass()) { try{ field =clazz.getDeclaredField(fieldName); } catch(NoSuchFieldException e) { log.warn("bean没有该属性,bean = " + clazz.getName() + ",属性 = " +fieldName); } } returnfield; } /** * 属性设值 * * @paramo 子类对象 * @paramfieldName 属性名 * @paramvalue 需要设置的属性值 */ public static voidsetFieldValue(Object o, String fieldName, Object value) { Field field =getDeclareField(o, fieldName); if (field != null) { field.setAccessible(true); try{ field.set(o, value); } catch(IllegalAccessException e) { e.printStackTrace(); } } else{ log.error("对象没有该属性,对象 = " + o.getClass() + " 属性 = " +fieldName); } } public staticObject getFieldName(Object o, String fieldName) { Field field =getDeclareField(o, fieldName); if (field != null) { field.setAccessible(true); try{ returnfield.get(o); } catch(IllegalAccessException e) { e.printStackTrace(); } } return null; } /** * 获取对象所有的属性,包括父类的属性 * * @paramo * @return */ public staticField[] getAllProperties(Object o) { Class clazz =o.getClass(); List<Field> fieldList = new ArrayList<>(); while (clazz != null) { fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz =clazz.getSuperclass(); } Field[] fields = newField[fieldList.size()]; fieldList.toArray(fields); returnfields; } }
通过反射查找子类、父类的属性(子类找不到则到父类找)
免责声明:文章转载自《通过反射查找子类、父类的属性(子类找不到则到父类找)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。
上篇JS获取一行2列的表格数据Tesseract识别图片提取文字&amp;字库训练下篇
宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=