package com.qckj.common.utils;
import cn.hutool.core.util.ObjectUtil;
import com.qckj.common.constants.CommonConstant;
import com.qckj.common.transfer.service.impl.StandardMap2BeanProcessorImpl;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import oracle.sql.CLOB;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Clob;
import java.text.SimpleDateFormat;
import java.util.*;
public class Tools {
public static Object convertMap(Class type, Map map)throws IntrospectionException, IllegalAccessException,
InstantiationException, InvocationTargetException {
BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
Object obj = type.newInstance(); // 创建 JavaBean 对象
// 给 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.toUpperCase())) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName.toUpperCase());
Class c = descriptor.getClass();
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(obj, args);
}
}
return obj;
}
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);
org.apache.commons.beanutils.BeanUtils.populate(obj, map);
return obj;
}
public static void main(String[] args) {
String a = toUnderScoreCase("UserName");
System.out.println(a);
}
/**
* 驼峰转下划线命名
*/
public static String toUnderScoreCase(String str)
{
if (str == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean curreCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (i > 0)
{
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
}
else
{
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1))
{
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
{
sb.append("_");
}
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
{
sb.append("_");
}
sb.append(Character.toUpperCase(c));
}
return sb.toString();
}
public static <T> T map2Object(Map<String, Object> map, Class<T> clazz) {
Map<String, String> result = new CaseInsensitiveMap(map);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (map == null) {
return null;
}
T obj = null;
try {
// 使用newInstance来创建对象
obj = clazz.newInstance();
// 获取类中的所有字段
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
// 判断是拥有某个修饰符
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
// 当字段使用private修饰时,需要加上
field.setAccessible(true);
// 获取参数类型名字
String filedTypeName = field.getType().getName();
// 判断是否为时间类型,使用equalsIgnoreCase比较字符串,不区分大小写
String filedName = field.getName();
String UnderScoreUpper = toUnderScoreCase(filedName);
Object val = ObjectUtil.isNotNull(result.get(filedName))?result.get(filedName):result.get(UnderScoreUpper);
// 给obj的属性赋值
if (filedTypeName.equalsIgnoreCase("java.util.date")) {
String datetimestamp = (String) val;
if (datetimestamp.equalsIgnoreCase("null")) {
field.set(obj, null);
} else {
field.set(obj, sdf.parse(datetimestamp));
}
} else {
field.set(obj, val);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public static Map camelCaseObjectToUnderScoreUpperCaseMap(Object bean){
Class type = bean.getClass();
Map returnMap = new LinkedHashMap();
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(toUnderScoreCase(propertyName), result);
} else {
returnMap.put(toUnderScoreCase(propertyName), "");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnMap;
}
public static Map ObjectToUpperCaseMap(Object bean){
Class type = bean.getClass();
Map returnMap = new LinkedHashMap();
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName.toUpperCase(), result);
} else {
returnMap.put(propertyName.toUpperCase(), "");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return returnMap;
}
public static Map<String, Object> transferToUpperCase(Map<String, Object> orgMap) {
Iterator entries = orgMap.entrySet().iterator();
Map<String, Object> resultMap = new HashMap<String, Object>();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
;
String name = (String) entry.getKey();
Object valueObj = entry.getValue();
if (valueObj instanceof ArrayList<?>) {
String StringObj = "";
List<Object> list = (ArrayList<Object>) valueObj;
for (int i = 0; i < list.size(); i++) {
StringObj = StringObj + list.get(i) + ",";
}
valueObj = StringObj.substring(0, StringObj.length() - 1);
//System.out.println("valueObj="+valueObj);
}
resultMap.put(name.toUpperCase(), valueObj);
}
return resultMap;
}
public static Map convertBean(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Class type = bean.getClass();
Map returnMap = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, "");
}
}
}
return returnMap;
}
public static Map convertBean_UpperCase(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Class type = bean.getClass();
Map returnMap = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName.toUpperCase(), result);
} else {
returnMap.put(propertyName.toUpperCase(), "");
}
}
}
return returnMap;
}
/**
* 获取指定字段名称查找在class中的对应的Field对象(包括查找父类)
*
* @param clazz 指定的class
* @param fieldName 字段名称
* @return Field对象
*/
private static Field getClassField(Class<?> clazz, String fieldName) {
if (Object.class.getName().equals(clazz.getName())) {
return null;
}
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {// 简单的递归一下
return getClassField(superClass, fieldName);
}
return null;
}
public static String getMaptoString(Map m, Object key) {
return m.get(key) != null ? m.get(key).toString() : "";
}
public static int getMaptoInt(Map m, Object key) {
return m.get(key) != null ? Integer.parseInt(m.get(key).toString()) : 0;
}
public static Integer getMaptoInteger(Map m, Object key) {
return m.get(key) != null ? (Integer) m.get(key) : 0;
}
public static MsgVo getSuccessResultJson(String message) {
MsgVo mv = new MsgVo();
mv.setCode(CommonConstant.SUCCESS_CODE);
mv.setStatus("success");
mv.setMessage(message);
return mv;
}
public static MsgVo getFailResultJson(String message) {
MsgVo mv = new MsgVo();
mv.setCode(CommonConstant.FAIL_CODE);
mv.setStatus("fail");
mv.setMessage(message);
return mv;
}
public static MsgVo error(String code,String msg) {
MsgVo mv = new MsgVo();
mv.setCode(code);
mv.setStatus("error");
mv.setMessage(msg);
return mv;
}
public static String getSuccessResultJson2(String message) {
Result r = new Result();
r.setSuccess(true);
r.setMessage(message);
r.setStatusCode(0);
return GsonUtil.toJson(r);
}
public static String getFailResultJson2(String message) {
Result r = new Result();
r.setSuccess(false);
r.setMessage(message);
r.setStatusCode(1);
return GsonUtil.toJson(r);
}
/**
* 读取txt里的单行内容
*
* @param fileP 文件路径
*/
public static String readTxtFile(String fileP) {
try {
String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("/"));//项目路径
//System.out.println("filePath="+filePath);
filePath = filePath.replaceAll("file:/", "");
filePath = filePath.replaceAll("%20", " ");
filePath = filePath.trim() + fileP.trim();
if (filePath.indexOf(":") != 1) {
filePath = File.separator + filePath;
}
String encoding = "utf-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding); // 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
return lineTxt;
}
read.close();
} else {
//System.out.println("找不到指定的文件,查看此路径是否正确:"+filePath);
}
} catch (Exception e) {
//System.out.println("读取文件内容出错");
}
return "";
}
/**
* 自动补零生成序列号
*/
public static String frontCompWithZore(String sourceDate, int formatLength, String sourceFlag) {
String newString = sourceFlag + String.format("%0" + formatLength + "d", Integer.valueOf(sourceDate));
return newString;
}
//字符串补0方法
public static String addZeroForNum(String str, int strLength) {
int strLen = str.length();
StringBuffer sb = null;
while (strLen < strLength) {
sb = new StringBuffer();
// sb.append("0").append(str);// 左(前)补0
sb.append(str).append("0");//右(后)补0
str = sb.toString();
strLen = str.length();
}
return str;
}
//字符串补0方法
public static String addZeroForNum_Left(String str, int strLength) {
int strLen = str.length();
StringBuffer sb = null;
while (strLen < strLength) {
sb = new StringBuffer();
sb.append("0").append(str);// 左(前)补0
//sb.append(str).append("0");//右(后)补0
str = sb.toString();
strLen = str.length();
}
return str;
}
public static CLOB parseOracleClob(Clob clob) {
// 解决Druid的坑
if (clob instanceof com.alibaba.druid.proxy.jdbc.ClobProxyImpl) {
com.alibaba.druid.proxy.jdbc.ClobProxyImpl impl = (com.alibaba.druid.proxy.jdbc.ClobProxyImpl) clob;
clob = impl.getRawClob(); // 获取原生的这个 Clob
}
return (CLOB) clob;
}
/**
* 得到中文首字母
*
* @param str
* @return
*/
public static String getPinYinHeadChar(String str) {
String convert = "";
for (int j = 0; j < str.length(); j++) {
char word = str.charAt(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert += pinyinArray[0].charAt(0);
} else {
convert += word;
}
}
return convert;
}
/**
* 汉字转为拼音
* @param chinese
* @return
*/
public static String ToPinyin(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < newChar.length; i++) {
if (newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
if(pinyinStr.indexOf("u:")>0){
pinyinStr = pinyinStr.replaceAll("u:", "v");
}
return pinyinStr;
}
/**
* List去重复元素
* @param list
* @return
*/
public static List removeDuplicate(List list) {
List listTemp = new ArrayList();
for (int i = 0; i < list.size(); i++) {
if (!listTemp.contains(list.get(i))) {
listTemp.add(list.get(i));
}
}
return listTemp;
}
/**
* 自定义 map->bean 映射TableField值
*/
public static <R> R map2BeanWithMapping(Map<? super Object, ? super Object> data, Class<R> outBeanClass, Object obj) {
return StandardMap2BeanProcessorImpl.map2BeanWithMapping(data,outBeanClass,obj);
}
/**
* 自定义 list->bean 映射TableField值
*/
public static <R> List<R> listMap2ListBeanWithMapping(List<Map<? super Object, ? super Object>> data, Class<R> outBeanClass, Object obj) {
return StandardMap2BeanProcessorImpl.listMap2ListBeanWithMapping(data,outBeanClass,obj);
}
}
处理map工具类
最新推荐文章于 2024-07-14 22:18:32 发布