一、ArrayUtil
package org.smart4j.framework.util;import org.apache.commons.lang3.ArrayUtils;public class ArrayUtil { /** * 判断数组是否非空 * @param array * @return */ public static boolean isNotEmpty(Object[] array){ return !ArrayUtils.isEmpty(array); } /** * 判断数组是否为空 * @param array * @return */ public static boolean isEmpty(Object[] array){ return ArrayUtils.isEmpty(array); } }
二、CastUtil
package org.smart4j.framework.util;/** * 转型操作工具类 * * @author huangyong * @since 1.0.0 */public final class CastUtil { /** * 转为 String 型 */ public static String castString(Object obj) { return CastUtil.castString(obj, ""); } /** * 转为 String 型(提供默认值) */ public static String castString(Object obj, String defaultValue) { return obj != null ? String.valueOf(obj) : defaultValue; } /** * 转为 double 型 */ public static double castDouble(Object obj) { return CastUtil.castDouble(obj, 0); } /** * 转为 double 型(提供默认值) */ public static double castDouble(Object obj, double defaultValue) { double doubleValue = defaultValue; if (obj != null) { String strValue = castString(obj); if (StringUtil.isNotEmpty(strValue)) { try { doubleValue = Double.parseDouble(strValue); } catch (NumberFormatException e) { doubleValue = defaultValue; } } } return doubleValue; } /** * 转为 long 型 */ public static long castLong(Object obj) { return CastUtil.castLong(obj, 0); } /** * 转为 long 型(提供默认值) */ public static long castLong(Object obj, long defaultValue) { long longValue = defaultValue; if (obj != null) { String strValue = castString(obj); if (StringUtil.isNotEmpty(strValue)) { try { longValue = Long.parseLong(strValue); } catch (NumberFormatException e) { longValue = defaultValue; } } } return longValue; } /** * 转为 int 型 */ public static int castInt(Object obj) { return CastUtil.castInt(obj, 0); } /** * 转为 int 型(提供默认值) */ public static int castInt(Object obj, int defaultValue) { int intValue = defaultValue; if (obj != null) { String strValue = castString(obj); if (StringUtil.isNotEmpty(strValue)) { try { intValue = Integer.parseInt(strValue); } catch (NumberFormatException e) { intValue = defaultValue; } } } return intValue; } /** * 转为 boolean 型 */ public static boolean castBoolean(Object obj) { return CastUtil.castBoolean(obj, false); } /** * 转为 boolean 型(提供默认值) */ public static boolean castBoolean(Object obj, boolean defaultValue) { boolean booleanValue = defaultValue; if (obj != null) { booleanValue = Boolean.parseBoolean(castString(obj)); } return booleanValue; }}
三、ClassUtil
package org.smart4j.framework.util;import java.io.File;import java.io.FileFilter;import java.io.IOException;import java.net.JarURLConnection;import java.net.URL;import java.util.Enumeration;import java.util.HashSet;import java.util.Set;import java.util.jar.JarEntry;import java.util.jar.JarFile;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.smart4j.framework.helper.ConfigHelper;/** * 类操作工具类 * @author TS * */public final class ClassUtil { private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class); /** * 获取当前线程中的类加载器 * @return ClassLoader对象 */ public static ClassLoader getClassLoader(){ return Thread.currentThread().getContextClassLoader(); } /** * 加载类 * @param className 类的全限定名 * @param isInitialied 是否初始化的标志(是否执行类的静态代码块)TODO * @return */ public static Class loadClass(String className,boolean isInitialied){ Class cls; try { cls = Class.forName(className, isInitialied, getClassLoader()); } catch (ClassNotFoundException e) { LOGGER.error("加载类初始化错误"); throw new RuntimeException(e); } return cls; } /** * 加载类 * @param className 类的全限定名 * @return */ public static Class loadClass(String className){ Class cls; try { cls = Class.forName(className); } catch (ClassNotFoundException e) { LOGGER.error("加载类初始化错误"); throw new RuntimeException(e); } return cls; } /** * 获取指定包名下的所有类 * @param packageName 包名 * @return Set* 1.根据包名将其转换为文件路径 * 2读取class或者jar包,获取指定的类名去加载类 */ public static Set > getClassSet(String packageName){ Set > classSet = new HashSet >(); try { Enumeration urls = getClassLoader().getResources(packageName.replace(".", "/")); if( urls.hasMoreElements() ){ URL url = urls.nextElement(); if(url != null ){ String protocol = url.getProtocol(); //协议名称 if( protocol.equals("file") ){ String packagePath = url.getPath().replace("%20", " "); //加载类 addClass(classSet,packagePath,packageName); }else if( protocol.equals("jar") ){ JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); if( jarURLConnection != null ){ JarFile jarFile = jarURLConnection.getJarFile(); if( jarFile != null ){ Enumeration jarEntries = jarFile.entries(); while ( jarEntries.hasMoreElements() ) { JarEntry jarEntry = jarEntries.nextElement(); String jarEntryName = jarEntry.getName(); if( jarEntryName.endsWith(".class") ){ String className = jarEntryName.substring(0,jarEntryName.lastIndexOf(".")).replaceAll("/", "."); doAddClass(classSet,className); } } } } } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return classSet; } private static void addClass(Set > classSet, String packagePath, String packageName) { File[] files = new File(packagePath).listFiles(new FileFilter() { @Override public boolean accept(File file) { return ( file.isFile() && file.getName().endsWith(".class") ) || file.isDirectory(); } }); for (File file : files) { String fileName = file.getName(); System.out.println(fileName); if( file.isFile() ){ String className = fileName.substring( 0,fileName.lastIndexOf(".") ); if( StringUtils.isNotEmpty(packageName) ){ className = packageName + "." + className; } doAddClass(classSet, className); } else { String subPackagePath = fileName; if( StringUtils.isNotEmpty(packagePath) ){ subPackagePath = packagePath + "/" + subPackagePath; } String subPackageName = fileName; if( StringUtils.isNotEmpty(subPackageName) ){ subPackageName = packageName + "." + subPackageName; } addClass(classSet, subPackagePath, subPackageName); } } } private static void doAddClass(Set > classSet, String className) { Class cls = loadClass(className, false); classSet.add(cls); } public static void main(String[] args) { ClassUtil.getClassSet(ConfigHelper.getAppBasePackage()); }}
四、CodecUtil
package org.smart4j.framework.util;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;/** * 编码与解码操作工具类 * @author TS * */public class CodecUtil { /** * 将URL编码 * @param source * @return */ public static String encodeURL(String source){ String target = null; try { target = URLEncoder.encode(source, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return target; } /** * 将URL解码 * @param source * @return */ public static String decodeURL(String source){ String target = null; try { target = URLDecoder.decode(source, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return target; }}
五、JsonUtil
package org.smart4j.framework.util;import com.fasterxml.jackson.databind.ObjectMapper;/** * 用于处理JSON与POJO之间的转换,基于Jackson实现 * @author TS * */public class JsonUtil { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); /** * 将POJO转化为JSON * @param obj * @return */ public staticString toJson(T obj){ String json; try{ json = OBJECT_MAPPER.writeValueAsString(obj); }catch(Exception e){ throw new RuntimeException(e); } return json; } /** * 将json转为pojo * @param json * @param type * @return */ public static T fromJson(String json,Class type){ T pojo; try{ pojo = OBJECT_MAPPER.readValue(json, type); }catch(Exception e){ throw new RuntimeException(e); } return pojo; }}
六、PropsUtil
package org.smart4j.framework.util;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * Properties文件读取工具类 * @author Admin * */public class PropsUtil { /** * 加载properties配置文件工具类 * @param fileConfig * @return */ public static Properties loadProps(String fileConfig){ Properties properties = new Properties(); try { InputStream in = Object.class.getResourceAsStream("/" + fileConfig); properties.load(in); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return properties; } /** * 根据传入的properties文件对象的key获得value * @param properties * @param key * @return value */ public static String getString(Properties properties,String key){ String value = properties.getProperty(key); return value; } /** * 根据传入的properties文件对象的key获得value,提供可选的路径配置项pathCustom * @param properties * @param key * @param pathCustom 自定义配置项,传入null默认加载配置文件key * @return value */ public static String getString(Properties properties,String key,String pathCustom){ if( pathCustom != null ){ return pathCustom; }else{ String value = properties.getProperty(key); return value; } }}
七、ReflectionUtil
package org.smart4j.framework.util;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * 反射工具类 * @author Admin * */public final class ReflectionUtil { private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class); /** * 创建实例 * @param cls * @return */ public static Object getInstance(Class cls){ Object instance; try { instance = cls.newInstance(); } catch (InstantiationException | IllegalAccessException e) { LOGGER.error("new instance failure",e); throw new RuntimeException(e); } return instance; } /** * 调用方法 * @param obj * @param method * @param args * @return */ public static Object invokeMethod(Object obj,Method method,Object ...args){ Object result; try { method.setAccessible(true); result = method.invoke(obj, args); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOGGER.error("invoke method failure",e); throw new RuntimeException(e); } return result; } /** * 设置成员变量的值 * @param obj * @param field * @param value */ public static void setField(Object obj,Field field,Object value){ field.setAccessible(true); try { field.set(obj, value); } catch (IllegalArgumentException | IllegalAccessException e) { LOGGER.error("set field failure",e); throw new RuntimeException(e); } }}
八、StreamUtil
package org.smart4j.framework.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;/** * 流操作工具类 * @author TS * */public class StreamUtil { /** * 获取流操作工具类 * @param in:输入流 * @return */ public static String getString(InputStream is){ StringBuilder sb = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); String line; while( (line = reader.readLine()) != null ){ sb.append(line); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); }}
九、StringUtil
package org.smart4j.framework.util;import org.apache.commons.lang3.StringUtils;import org.apache.commons.lang3.math.NumberUtils;/** * 字符串工具类 * * @author huangyong * @since 1.0.0 */public final class StringUtil { /** * 判断字符串是否为空 */ public static boolean isEmpty(String str) { if (str != null) { str = str.trim(); } return StringUtils.isEmpty(str); } /** * 判断字符串是否非空 */ public static boolean isNotEmpty(String str) { return !isEmpty(str); } /** * 判断字符串是否为数字 */ public static boolean isNumeric(String str) { return NumberUtils.isDigits(str); } /** * 正向查找指定字符串 */ public static int indexOf(String str, String searchStr, boolean ignoreCase) { if (ignoreCase) { return StringUtils.indexOfIgnoreCase(str, searchStr); } else { return str.indexOf(searchStr); } } /** * 反向查找指定字符串 */ public static int lastIndexOf(String str, String searchStr, boolean ignoreCase) { if (ignoreCase) { return StringUtils.lastIndexOfIgnoreCase(str, searchStr); } else { return str.lastIndexOf(searchStr); } } /** * 截取字符串 * @param body * @param string * @return */ public static String[] splitString(String body, String regex) { return body.split(regex); } }