從0開始寫JavaWeb框架系列(8)從0開始寫SamrtFrameWork:項目使用的工具類一覽

1、ArrayUtiljava

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);
	}
	
}

2、CastUtilgit

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;
    }
}

3、ClassUtilapache

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<Class>
	 * 1.根據包名將其轉換爲文件路徑
	 * 2讀取class或者jar包,獲取指定的類名去加載類
	 */
	public static Set<Class<?>> getClassSet(String packageName){
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		try {

			Enumeration<URL> 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<JarEntry> 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<Class<?>> 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<Class<?>> classSet, String className) {
		Class<?> cls = loadClass(className, false);
		classSet.add(cls);
	}

	public static void main(String[] args) {
		ClassUtil.getClassSet(ConfigHelper.getAppBasePackage());
	}
}

4、CodecUtiljson

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;
	}
}

5、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 static <T> String 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> T fromJson(String json,Class<T> type){
		T pojo;
		try{
			pojo = OBJECT_MAPPER.readValue(json, type);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
		 
		return pojo;
	}
}

6、PropsUtilapp

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;
		}
	}

}

7、ReflectionUtilide

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);
		}
	}


}

8、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();
	}
}

9、StringUtilui

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);
	}
    
    
   
}
相關文章
相關標籤/搜索