验证/格式转换工具

import java.beans.BeanInfo;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.shiro.crypto.hash.Hash;

import com.alibaba.fastjson.JSON;

public class Tools {

/**
* 随机生成六位数验证码
*
* @return
*/
public static int getRandomNum() {
Random r = new Random();
return r.nextInt(900000) + 100000;// (Math.random()*(999999-100000)+100000)
}

/**
* 检测字符串是否不为空(null,"","null")
*
* @param s
* @return 不为空则返回true,否则返回false
*/
public static boolean notEmpty(String s) {
return s != null && !"".equals(s) && !"null".equals(s);
}

/**
* 检测字符串是否为空(null,"","null")
*
* @param s
* @return 为空则返回true,不否则返回false
*/
public static boolean isEmpty(String s) {
return s == null || "".equals(s) || "null".equals(s);
}

/**
* 字符串转换为字符串数组
*
* @param str
* 字符串
* @param splitRegex
* 分隔符
* @return
*/
public static String[] str2StrArray(String str, String splitRegex) {
if (isEmpty(str)) {
return null;
}
return str.split(splitRegex);
}

/**
* 用默认的分隔符(,)将字符串转换为字符串数组
*
* @param str
* 字符串
* @return
*/
public static String[] str2StrArray(String str) {
return str2StrArray(str, ",\s*");
}

/**
* 按照yyyy-MM-dd HH:mm:ss的格式,日期转字符串
*
* @param date
* @return yyyy-MM-dd HH:mm:ss
*/
public static String date2Str(Date date) {
return date2Str(date, "yyyy-MM-dd HH:mm:ss");
}

/**
* 按照yyyy-MM-dd HH:mm:ss的格式,字符串转日期
*
* @param date
* @return
*/
public static Date str2Date(String date) {
if (notEmpty(date)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new Date();
} else {
return null;
}
}

/**
* 获取TimeStampleix
*
* @param date
* @return
*/
public static Timestamp getTimeStamp(String date) {
Timestamp d = null;
try {
d = Timestamp.valueOf(date2Str(str2Date(date)));
} catch (Exception e) {
return null;
}
return d;
}

/**
* 按照参数format的格式,日期转字符串
*
* @param date
* @param format
* @return
*/
public static String date2Str(Date date, String format) {
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
} else {
return "";
}
}

/**
* 实体类转为map
*
* @param obj
* 实体对象
* @return
*/
public static Map EntityToMap(Object obj) {
Map<String, Object> map = JSON.parseObject(JSON.toJSONString(obj));
for (String str : map.keySet()) {
map.put(str, String.valueOf(map.get(str)));
}
return map;
}

/**
* 把时间根据时、分、秒转换为时间段
*
* @param StrDate
*/
public static String getTimes(String StrDate) {
String resultTimes = "";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date now;
try {
now = new Date();
java.util.Date date = df.parse(StrDate);
long times = now.getTime() - date.getTime();
long day = times / (24 * 60 * 60 * 1000);
long hour = (times / (60 * 60 * 1000) - day * 24);
long min = ((times / (60 * 1000)) - day * 24 * 60 - hour * 60);
long sec = (times / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

StringBuffer sb = new StringBuffer();
// sb.append("发表于:");
if (hour > 0) {
sb.append(hour + "小时前");
} else if (min > 0) {
sb.append(min + "分钟前");
} else {
sb.append(sec + "秒前");
}
resultTimes = sb.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return resultTimes;
}

public static void main(String[] args) {
System.out.println(getRandomNum());
}

// 获得 数据库列名-值 key-value形式
public static Map<String, Object> getFileAndCoulm(Object d) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
// 通过反射机制,判断传入的实体类中的那个属性值不为空,动态作为条件查询
Class c = d.getClass();
Field[] fs = c.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
if (f != null) {
String fileName = f.getName();
// 获取每一个值没
Object v = invokeMethod(d, f.getName(), null);
// 如果值不为空
if (null != v && !"".equals(v.toString())) {
map.put(fileName, v.toString());
} else {
map.put(fileName, "");
}
}
}
return map;
}


// 获得 数据库列名-值 key-value形式
public static List<Map<String,Object>> getFileAndCoulmByList(List list) throws Exception {
if(list==null||list.isEmpty()) {
return null;
}
List<Map<String,Object>> mapList =new ArrayList<>();
for (int j = 0; j < list.size(); j++) {
Map<String, Object> map = new HashMap<String, Object>();
// 通过反射机制,判断传入的实体类中的那个属性值不为空,动态作为条件查询
Class c = list.get(j).getClass();
Field[] fs = c.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
if (f != null) {
String fileName = f.getName();
// 获取每一个值没
Object v = invokeMethod(list.get(j), f.getName(), null);
// 如果值不为空
if (null != v && !"".equals(v.toString())) {
map.put(fileName, v.toString());
} else {
map.put(fileName, "");
}
}
}
mapList.add(map);
}
return mapList;
}

private static Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception {
Class ownerClass = owner.getClass();
methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
Method method = null;
try {
method = ownerClass.getMethod("get" + methodName);
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
return " can't find 'get" + methodName + "' method";
}
return method.invoke(owner);
}


public static String addNode(String str,String queueName)
{

StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append(""type":").append(queueName);
sb.append(","data":").append(str);
sb.append("}");
return sb.toString();

}


/**
* Map转成实体对象
* @param map map实体对象包含属性
* @param clazz 实体对象类型
* @return
*/
public Object map2Object(Map<String, Object> map, Class<?> clazz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = clazz.newInstance();

Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName().toLowerCase()));
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
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.replace("_", "").toLowerCase())||map.containsKey(propertyName.replace("_", "").toUpperCase())) {
try {
Object value = map.get(propertyName);

Object[] args = new Object[1];
args[0] = value;

descriptor.getWriteMethod().invoke(obj, args);
} catch (IllegalArgumentException e) {
continue;
}
}
}
return obj;
}
}

原文地址:https://www.cnblogs.com/Sora-L/p/9515938.html