com.myb.common.util.BeanUtil Maven / Gradle / Ivy
package com.myb.common.util;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @Author meiyubin
* @Date 2023/12/6
* @DESC
*/
@Component
public class BeanUtil {
/**
* 将任意类型转换成字符串
*
* @param value
* @param
* @return
*/
public static String beanToString(T value) {
Class> clazz = value.getClass();
if (clazz == int.class || clazz == Integer.class) {
return value + "";
} else if (clazz == String.class) {
return (String) value;
} else if (clazz == long.class || clazz == Long.class) {
return value + "";
} else {
return JSONUtil.toJsonStr(value);
}
}
/**
* 把一个字符串转换成bean对象
*
* @param str
* @param
* @return
*/
@SuppressWarnings("unchecked")
public static T stringToBean(String str, Class clazz) {
if (str == null || str.length() <= 0 || clazz == null) {
return null;
}
if (clazz == int.class || clazz == Integer.class) {
return (T) Integer.valueOf(str);
} else if (clazz == String.class) {
return (T) str;
} else if (clazz == long.class || clazz == Long.class) {
return (T) Long.valueOf(str);
} else {
return JSONUtil.toBean(JSONUtil.parse(str).toString(), clazz);
}
}
/**
* List 转换成 List 直接copy
*
* @param sourceList
* @param targetClass
* @return List
* @author meiyubin
*/
public static List convertToVOList(List sourceList, Class targetClass) {
List targetList = new ArrayList<>();
for (T source : sourceList) {
try {
V target = targetClass.newInstance();
BeanUtils.copyProperties(source, target);
targetList.add(target);
} catch (InstantiationException | IllegalAccessException e) {
// 处理异常
}
}
return targetList;
}
/**
* 实体直接copy
*
* @param source
* @param targetClass
* @return V
* @author meiyubin
*/
public static V convertToVO(T source, Class targetClass) {
try {
V target = targetClass.newInstance();
BeanUtils.copyProperties(source, target);
return target;
} catch (InstantiationException | IllegalAccessException e) {
// 处理异常
}
return null;
}
}