/** * 从对象中动态获取属性值 * @param obj 对象 * @param name 要获取的属性值 * @return */ private static Object getObjectInfo(Object obj,String name){ Object value = new Object(); try { Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); value=field.get(obj); } catch (Exception e){ e.getStackTrace(); } return value; }
public static void main(String[] args){ CatPo catPo = CatPo.builder() .color("蓝色") .build(); String color = String.valueOf(getObjectInfo(catPo,"color")); System.out.println(color); }
结果: