package com.pbh.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @ClassName: EntityFieldUtil
* @Description: TODO(泛型bean操作类)
* @author PanBaihui
* @date 2017年8月19日 下午11:29:18
*
*/
public class EntityFieldUtil {
/**
*
* @Title: replaceNullToString
* @Description: 将entity内String类型返回值为null更改为""
* @author PanBaihui
* @time 2017年8月31日 下午2:14:58
* @param entity
* @return
* @throws
*/
@Transactional(readOnly=true)
public static <T> T replaceNullToString(T entity) {
Class entityClass = (Class) entity.getClass();
Method[] methods = entityClass.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
int index = method.getReturnType().toString().indexOf("String");
if (index > -1) {
String methodName = method.getName();
if (methodName.startsWith("get")) {
try {
Object value = method.invoke(entity);
if (value == null) {
String setMethodName = methodName.replace("get", "set");
Method setMethod = entityClass.getMethod(setMethodName,String.class);
setMethod.invoke(entity,"");
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
}
return entity;
}
/**
*
* @Title: replaceNullToString
* @Description: 将entitys内String类型返回值为null更改为""
* @author PanBaihui
* @time 2017年8月31日 下午3:10:13
* @param entitys
* @return List<T>
* @throws
*/
public static <T> List<T> replaceNullToString(List<T> entitys) {
List<T> newList = new ArrayList<>();
for (T t : entitys) {
newList.add(replaceNullToString(t));
}
return newList;
}
/**
*
* @Title: getFieldName
* @Description: TODO(根据get或set方法返回属性名)
* @param methodName
* @param replace
* @return String 返回类型
*/
public static String getFieldName(String methodName, String replace) {
methodName = methodName.replace(replace, "");
return methodName.substring(0, 1).toLowerCase() + methodName.substring(1);
}
}