java 获取属性值和设置属性值
/**
获取一个对象里的全部属性
List<String> pInfoFields = Arrays.stream(pInfo.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
*/
/** * 获取属性值 * @param obj * @param property * @return */ public static Object getObjProVal(Object obj, String property) { Object val = null; int len = property.length(); String methodName = "get" + property.substring(0, 1).toUpperCase() + property.substring(1, len); try { Method method = obj.getClass().getMethod(methodName); val = method.invoke(obj); } catch (Exception e) { } return val; } /** * 设置属性值 * @param obj * @param property * @param value * @return */ public static void setObjProVal(Object obj, String property, Object value) { int len = property.length(); String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1, len); try { Method method = obj.getClass().getMethod(methodName, value.getClass()); method.invoke(obj, value); } catch (Exception e) { e.printStackTrace(); } }
随笔看心情