公司使用JFinal框架,发现JFinal中Record数据无法通过fastjson直接转实体类对象,只能使用record各种get获取数据,实在是无法忍受,写了一个处理record的工具类(还需完善)
public class RecordUtils {
/**
* Record转JavaBean
*
* @param record Record对象
* @param clazz 实体类Class
* @param <T> 泛型
* @return 对应实体类
* @throws Exception 抛出异常
*/
public static <T> T parseObject(Record record, Class<T> clazz) throws Exception{
if (record == null){
return null;
}
T obj = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String fieldName = field.getName();
field.setAccessible(true);
Object o = record.get(fieldName);
if (o != null) {
if (field.getType().toString().equals("class java.time.LocalDateTime")) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
LocalDateTime ldt = LocalDateTime.from(df.parse(o.toString()));
field.set(obj, ldt);
} else {
field.set(obj, o);
}
}
}
return obj;
}
/**
* Record对象集合转为实体类List集合
*
* @param recordList Record对象
* @param clazz 实体类
* @param <T> 泛型
* @return 实体类List集合
* @throws Exception 抛出异常
*/
public static <T> List<T> parseArray(List<Record> recordList, Class<T> clazz) throws Exception{
if (recordList == null || recordList.size() == 0){
return null;
}
List<T> list = new ArrayList<>();
for (Record record : recordList){
list.add(parseObject(record, clazz));
}
return list;
}
/**
* JavaBean转Record
*
* @param obj 实体类对象
* @return Record对象
* @throws Exception 抛出异常
*/
public static Record javaBeanToRecord(Object obj) throws Exception{
if(obj == null){
return null;
}
Record record = new Record();
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
record.set(field.getName(), field.get(obj));
}
return record;
}
/**
* Model转Map
*
* @param model Model数据
* @return Map数据
*/
public static Map<String,Object> modelToMap(Model model){
if(model == null){
return null;
}
Map<String,Object> tempMap = new HashMap<>();
String[] keys = model._getAttrNames();
for (String key : keys) {
tempMap.put(key, model.get(key));
}
return tempMap;
}
/**
* Record是否为空
*
* @param record Record对象
* @return 是否为空
*/
public static boolean isEmpty(Record record){
if (record == null){
return true;
}
return record.getColumnNames().length == 0;
}
/**
* List集合是否为空
*
* @param list List集合
* @return 是否为空
*/
public static boolean isEmpty(List<Record> list){
if (list == null){
return true;
}
return list.isEmpty();
}
/**
* List集合Record转Map
*
* @param list Record的List集合
* @return Map集合
*/
public static List<Map<String,Object>> recordListToMapList(List<Record> list){
if (isEmpty(list)){
return null;
}
List<Map<String,Object>> tempList = new ArrayList<>();
for (Record record : list) {
tempList.add(record.getColumns());
}
return tempList;
}
/**
* 获取value值字符串
*
* @param record 集合数据
* @param key key值
* @return value字符串
*/
public static String getStr(Record record, String key){
if (record == null || record.get(key) == null){
return null;
}
return record.get(key).toString();
}
}