@Data
@NoArgsConstructor
public class Car {
private String brand;
private String type;
public Car(String brand, String type) {
this.brand = brand;
this.type = type;
}
}
@Test
public void test18() {
Car car = new Car("12", "12");
System.out.println(JSON.toJSONString(setConditionMap(car)));
}
public static Map<String, Object> setConditionMap(Object obj){
Map<String, Object> map = new HashMap<>();
if(obj==null){
return null;
}
Field[] fields = obj.getClass().getDeclaredFields();
for(Field field : fields){
String fieldName = field.getName();
if(getValueByFieldName(fieldName,obj)!=null)
{
map.put(fieldName, getValueByFieldName(fieldName,obj));
}
}
return map;
}
public static Object getValueByFieldName(String fieldName,Object object){
String firstLetter=fieldName.substring(0,1).toUpperCase();
String getter = "get"+firstLetter+fieldName.substring(1);
try {
Method method = object.getClass().getMethod(getter);
return method.invoke(object);
} catch (Exception e) {
return null;
}
}
将java bean转换成Map类型
最新推荐文章于 2025-06-23 16:40:09 发布