本文共 2083 字,大约阅读时间需要 6 分钟。
本文将详细介绍两个核心功能:Bean转Map与Map转Bean。通过代码示例和对注解的解读,阐述实现原理与应用场景。
public static Mapbean2Map(T source) throws IllegalAccessException { Map result = new HashMap<>(); Class sourceClass = source.getClass(); Field[] sourceFields = sourceClass.getDeclaredFields(); for (Field field : sourceFields) { field.setAccessible(true); FieldName fieldNameAnnotation = field.getAnnotation(FieldName.class); if (fieldNameAnnotation == null) { result.put(field.getName(), field.get(source)); } else { if (!fieldNameAnnotation.Ignore()) { String headerName = fieldNameAnnotation.value(); result.put(headerName, field.get(source)); } } } return result;}
@FieldName
注解用于自定义字段名,支持忽略某些字段。字段名默认为空,忽略标志默认为false
。
public static T map2Bean(Mapsource, Class instance) { try { T object = instance.newInstance(); Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); FieldName fieldNameAnnotation = field.getAnnotation(FieldName.class); if (fieldNameAnnotation != null) { String headerName = fieldNameAnnotation.value(); Object value = source.get(headerName); field.set(object, value); } else { String fieldName = field.getName(); Object value = source.get(fieldName); field.set(object, value); } } return object; } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null;}
同样,@FieldName
用于自定义字段名,支持忽略某些字段。字段名默认为空,忽略标志默认为false
。
setAccessible(true)
确保可访问。转载地址:http://ogufk.baihongyu.com/