Skip to content

Instantly share code, notes, and snippets.

@HydrangeaPurple
Created March 9, 2021 03:50
Show Gist options
  • Save HydrangeaPurple/80ab769c7c630a7edf973192542cc37f to your computer and use it in GitHub Desktop.
Save HydrangeaPurple/80ab769c7c630a7edf973192542cc37f to your computer and use it in GitHub Desktop.
java bean 与map互转
@Slf4j
public class BeanUtils {
//region MapToBeanBySet
/**
* map里的参数反射到Bean
* @param map
* @param clazz
* @param <T>
* @return
*/
public static <T>T map2BeanBySet(Map map,Class<T> clazz){
return mapToBeanBySet(map,clazz);
}
public static <T>T mapToBeanBySet(Map map,Class<T> clazz){
T bean=null;
try {
bean=clazz.newInstance();
BeanInfo beanInfo = null;
beanInfo = Introspector.getBeanInfo(clazz);
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i< propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (map.containsKey(propertyName)) {
try {
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(bean, args);
}catch (Exception e){
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
// } catch (InstantiationException e) {
// e.printStackTrace();
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// } catch (IntrospectionException e) {
// e.printStackTrace();
}
return bean;
}
//endregion
//region MapToBeanByField
/**
* map里的参数反射到Bean
* @param map
* @param clazz
* @param <T>
* @return
*/
public static <T>T map2BeanByField(Map map,Class<T> clazz){
return mapToBeanByField(map,clazz);
}
public static <T>T mapToBeanByField(Map map,Class<T> clazz){
T bean=null;
try {
Field[] fields=getAllDeclaredFields(clazz);
if(fields==null||fields.length==0){
return bean;
}
bean=clazz.newInstance();
for(Field field:fields){
//重置属性可见(而且一般属性都是私有的),否则操作无效
boolean accessible = field.isAccessible();
if(!accessible){
field.setAccessible(true);
}
//获取属性名称
String key = field.getName();
try {
field.set(bean,map.get(key));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//还原属性标识
field.setAccessible(accessible);
}
}catch (Exception e){
e.printStackTrace();
}
return bean;
}
//endregion
//region beanToBeanSet
public static <T>T bean2BeanBySet(Object bean,Class<T> clazz)throws Exception{
return beanToBeanBySet(bean,clazz);
}
public static <T>T beanToBeanBySet(Object bean,Class<T> clazz)throws Exception{
return mapToBeanBySet(beanToMapByGet(bean),clazz);
}
//endregion
//region beanToBeanField
public static <T>T bean2BeanByField(Object bean,Class<T> clazz)throws Exception{
return beanToBeanByField(bean,clazz);
}
public static <T>T beanToBeanByField(Object bean,Class<T> clazz)throws Exception{
return mapToBeanByField(beanToMapByGet(bean),clazz);
}
//endregion
//region beanToMapByGet 各种重载
/**
* 将某个类属性添加到Map中
* ByGet是基于get方法获取值,所以会出现2种异常情况
* 1.bean的属性没get方法 那获取不到此属性的值
* 2.bean里有get方法,但是bean没有此属性,那map里会有此key-value
* @param bean
* @return
* @throws Exception
*/
public static Map<String,Object> bean2MapByGet(Object bean) throws Exception {
return beanToMapByGet(bean,null);
}
public static Map<String,Object> beanToMapByGet(Object bean) throws Exception {
return beanToMapByGet(bean,null);
}
//endregion
//region beanToMapByGet 基础工具
/**
* 将某个类属性添加到Map中
* ByGet是基于get方法获取值,所以会出现2种异常情况
* 1.bean的属性没get方法 那获取不到此属性的值
* 2.bean里有get方法,但是bean没有此属性,那map里会有此key-value
* @param bean
* @param excludes 排除字段
* @return
* @throws Exception
*/
public static Map<String,Object> beanToMapByGet(Object bean,String[] excludes) throws Exception {
Set<String> excludeSet = null;
Map<String,Object> returnMap = new LinkedHashMap();
Class clazz = bean.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
if(excludes != null&&excludes.length>0){
excludeSet=new HashSet<String>();
for(String exclude : excludes){
excludeSet.add(exclude);
}
}
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
if (readMethod == null)//若没有读方法,不进行设值
continue;
if(excludeSet!=null&&excludeSet.contains(propertyName))//排除字段
continue;
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, null);
}
}
}
return returnMap;
}
//endregion
//region beanToMapByField 各种重载
/**
* 将某个类属性添加到Map中
* 下面是各种名称方便查询和使用
* @param bean
* @return
*/
public static Map<String,Object> bean2MapByField(Object bean){
return beanToMapByField(bean,false,null);
}
public static Map<String,Object> beanToMapByField(Object bean){
return beanToMapByField(bean,false,null);
}
/**
* 将某个类属性添加到Map中
* @param bean
* @param excludes 排除字段
* @return
*/
public static Map<String,Object> bean2MapByField(Object bean,String[] excludes){
return beanToMapByField(bean,false,excludes);
}
public static Map<String,Object> beanToMapByField(Object bean,String[] excludes){
return beanToMapByField(bean,false,excludes);
}
/**
* 将某个类属性添加到Map中
* ByField是基于类的参数
* @param bean
* @param isDeep 是否获取父类属性
* @return
*/
public static Map<String,Object> bean2MapByField(Object bean,Boolean isDeep){
return beanToMapByField(bean,isDeep,null);
}
public static Map<String,Object> beanToMapByField(Object bean,Boolean isDeep){
return beanToMapByField(bean,isDeep,null);
}
//endregion
//region beanToMapByField 基础工具
/**
* 将某个类属性添加到Map中
* ByField是基于类的参数
* @param bean
* @param isDeep 是否获取父类属性
* @param excludes 排除字段
* @return
*/
public static Map<String,Object> beanToMapByField(Object bean,Boolean isDeep,String[] excludes){
Map<String,Object> result = new LinkedHashMap<String,Object>();
if(bean==null){
return result;
}
Field[] fields = null;
if (isDeep!=null&&isDeep){
fields=getAllDeclaredFields(bean.getClass());
}else {
fields=bean.getClass().getDeclaredFields();
}
if(fields==null||fields.length==0){
return result;
}
Set<String> excludeSet = null;
if(excludes != null&&excludes.length>0){
excludeSet=new HashSet<String>();
for(String exclude : excludes){
excludeSet.add(exclude);
}
}
for(Field field:fields){
//重置属性可见(而且一般属性都是私有的),否则操作无效
boolean accessible = field.isAccessible();
if(!accessible){
field.setAccessible(true);
}
//获取属性名称及值存入Map
String key = field.getName();
try {
if(excludeSet!=null&&excludeSet.contains(key))//排除字段
continue;
result.put(key, field.get(bean));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//还原属性标识
field.setAccessible(accessible);
}
return result;
}
//endregion
//region +++++ bean 工具类基石
/**
* 获取所有类属性(包括继承的)
* @param clazz
* @return
*/
public static Field[] getAllDeclaredFields(Class clazz) {
List<Field> allFields = new ArrayList<>();
while (!Object.class.equals(clazz) && clazz != null) {
allFields.addAll(Arrays.asList(clazz .getDeclaredFields()));
clazz = clazz.getSuperclass();
}
for (int i = 0; i < allFields.size() - 1; i++) {//如果子类与父类属性相同移除重复
for (int j = allFields.size() - 1; j > i; j--) {
if (allFields.get(j).getName().equals(allFields.get(i).getName())) {
allFields.remove(j);
}
}
}
Field[] fields = (Field[]) allFields.toArray(new Field[allFields.size()]);
return fields;
}
//endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment