關注 wx:CodingTechWork
需求
在Java開發代碼中,經常會有一些對象Bean轉換的需求,如下進行模板總結。
模板
public class BeansUtils {
/**
* Object to bean
*
* @param obj
* @param t
* @param <T>
* @return
*/
public static <T> T objToBean(Object obj, Class<T> t) {
//判空
if (null != obj) {
//轉jsonStr
String jsonStr = JSONObject.toJSONString(obj);
//json string對應bean
return JSONObject.parseObject(jsonStr, t);
}
//返回null
return null;
}
/**
* 解析obj爲string
*
* @param obj
* @return
*/
public static String objToString(Object obj) {
if (null != obj) {
return JSONObject.toJSON(obj).toString();
}
return null;
}
/**
* 拷貝soruces list對象到target對象中
*
* @param sources
* @param target
* @param <S>
* @param <T>
* @return
*/
public static <S, T> List<T> copyList(List<S> sources, Supplier<T> target) {
List<T> list = new ArrayList<>(sources.size());
for (S source : sources) {
T t = target.get();
BeanUtils.copyProperties(source, t);
list.add(t);
}
return list;
}
}