java常用工具類
java中有用的工具集
任何語言都要處理日期,map型別,字串,數字型別的資料,這裡找到一些用java經常處理這些資料的常用工具類,以便參考
一 VO工具集
package com.sds.faro.common.util;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
public class VoUtil {
/**
* Map? VO? ?????? ???( Vo Class? Method-Argument-Type? ???? Map? ??? ???(Cast) ??.
* non-enoding
* @param map
* @param objClass VO Class
* @return
*/
public static Object convertMapToObject(Map<?, ?> map, Object objClass) {
return convertMapToObject(map, objClass, false);
}
/**
* Map? VO? ?????? ???( Vo Class? Method-Argument-Type? ???? Map? ??? ???(Cast) ??.
* @param map
* @param objClass VO Class
* @param encoding ( convert 8859_1 -> UTF-8 )
* @return
*/
public static Object convertMapToObject(Map<?, ?> map, Object objClass, boolean encoding) {
if(map==null) return null;
String keyAttribute = null;
String setMethodString = "set";
String methodString = null;
Iterator<?> itr = map.keySet().iterator();
while (itr.hasNext()) {
keyAttribute = (String) itr.next();
if(keyAttribute.length()<1) {
continue;
}
methodString = setMethodString
+ keyAttribute.substring(0, 1).toUpperCase()
+ keyAttribute.substring(1);
try {
Method[] methods = objClass.getClass().getDeclaredMethods();
Class<?> methodType = null;
for (int i = 0; i <= methods.length - 1; i++) {
if (methodString.equals(methods[i].getName())) {
Object paramValue = "";
methodType = methods[i].getParameterTypes()[0];
/*
paramValue = map.get(keyAttribute);
System.out.println("methodString : ["+ methodString +"]"
+" / methods[i].getParameterTypes()[0].getName() : ["+ methods[i].getParameterTypes()[0].getName() +"]"
+" / keyAttribute : ["+ keyAttribute +"]"
+" / paramValue : ["+ (paramValue!=null? paramValue.toString():null) +"]"
+" / map.get(keyAttribute) : ["+ map.get(keyAttribute) +"]");
*/
if(map.get(keyAttribute) instanceof String[]){
String[] paramValueArr = (String[]) (map.get(keyAttribute));
paramValue = paramValueArr[0];
if(encoding)
paramValue = new String(((String)paramValue).getBytes("8859_1"), "utf-8");
}
else if(map.get(keyAttribute) instanceof String){
paramValue = (String)(map.get(keyAttribute));
if(encoding)
paramValue = new String(((String)paramValue).getBytes("8859_1"), "utf-8");
}
else if(map.get(keyAttribute) instanceof Integer){
paramValue = (Integer)(map.get(keyAttribute));
}
else if(map.get(keyAttribute) instanceof Long){
paramValue = (Long)(map.get(keyAttribute));
}
else if(map.get(keyAttribute) instanceof Float){
paramValue = (Float)(map.get(keyAttribute));
}
else if(map.get(keyAttribute) instanceof Double){
paramValue = (Double)(map.get(keyAttribute));
}
else if(map.get(keyAttribute) instanceof Boolean){
paramValue = (String)(map.get(keyAttribute));
}
else {
paramValue = (String)(map.get(keyAttribute));
}
if(methodType.equals(String.class)){
String theType = "java.lang.String";
Class<? extends String> castClass = Class.forName(theType).asSubclass(String.class);
if(encoding) {
paramValue = new String(((String)paramValue).getBytes("8859_1"), "utf-8");
}
String obj = null;
if(paramValue != null && !paramValue.toString().equals("")){
obj = castClass.cast(paramValue.toString());
}else{
obj = null;
}
methods[i].invoke(objClass, obj);
}
else if(methodType.equals(int.class) || methodType.equals(Integer.class)){
String theType = "java.lang.Number";
Class<? extends Number> castClass = Class.forName(theType).asSubclass(Number.class);
Number obj = null;
if(paramValue != null && !paramValue.toString().equals("")){
obj = castClass.cast(Integer.parseInt(paramValue.toString().replaceAll(",","")));
}else{
obj = new Integer(0);
}
methods[i].invoke(objClass, obj);
}
else if(methodType.equals(long.class) || methodType.equals(Long.class)){
String theType = "java.lang.Long";
Class<? extends Long> castClass = Class.forName(theType).asSubclass(Long.class);
Long obj = null;
if(paramValue != null && !paramValue.toString().equals("")){
obj = castClass.cast(Long.parseLong(paramValue.toString().replaceAll(",","")));
}else{
obj = new Long(0);
}
methods[i].invoke(objClass, obj);
}
else if(methodType.equals(float.class) || methodType.equals(Float.class)){
String theType = "java.lang.Float";
Class<? extends Float> castClass = Class.forName(theType).asSubclass(Float.class);
float obj = 0;
if(paramValue != null && !paramValue.toString().equals("")){
obj = castClass.cast(Float.parseFloat(paramValue.toString().replaceAll(",","")));
}else{
obj = new Float(0);
}
methods[i].invoke(objClass, obj);
}
else if(methodType.equals(double.class) || methodType.equals(Double.class)){
String theType = "java.lang.Double";
Class<? extends Double> castClass = Class.forName(theType).asSubclass(Double.class);
double obj = 0;
if(paramValue != null && !paramValue.toString().equals("")){
obj = castClass.cast(Double.parseDouble(paramValue.toString().replaceAll(",","")));
}else{
obj = new Double(0);
}
methods[i].invoke(objClass, obj);
}
else if(methodType.equals(Date.class)){
String theType = "java.util.Date";
Class<? extends Date> castClass = Class.forName(theType).asSubclass(Date.class);
Date obj = null;
if(paramValue != null && !paramValue.toString().equals("")){
obj = castClass.cast(DateUtil.getDateForJson(paramValue.toString()));
}else{
obj = null;
}
methods[i].invoke(objClass, obj);
}
else if(methodType.equals(boolean.class) || methodType.equals(Boolean.class)){
String theType = "java.lang.Boolean";
Class<? extends String> castClass = Class.forName(theType).asSubclass(String.class);
String obj = null;
if(paramValue != null && !paramValue.toString().equals("")){
if(((String)paramValue).equalsIgnoreCase("false")) {
obj = castClass.cast(Boolean.FALSE);
}
else if(((String)paramValue).equalsIgnoreCase("true")) {
obj = castClass.cast(Boolean.TRUE);
}
else {
obj = null;
}
}else{
obj = null;
}
methods[i].invoke(objClass, obj);
}
else{
//System.out.println("fail cast - methodString : ["+ methodString +"] / methods[i].getParameterTypes()[0].getName() : ["+ methods[i].getParameterTypes()[0].getName() +"]");
//System.out.println("fail cast - paramValue [" + paramValue +"]");
methods[i].invoke(objClass, paramValue);
}
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return objClass;
}
}
使用方法
想要接收前臺傳來的list 裡面存的是物件,後臺用list接收,list裡存的時Map
這時需要把後臺list裡的map轉換成物件,因此用到vo工具轉換map為物件方法
@RequestBody Map<String, Object> reqParam 傳過來的引數
List<Map<String, Object>> saveMdEmlMngVoList = (List<Map<String, Object>>) reqParam.get("reqListData");
for(int i=0; saveMdEmlMngVoList!=null && i<saveMdEmlMngVoList.size(); i++) {
MdEmlMngVo saveVo = (MdEmlMngVo)VoUtil.convertMapToObject((Map<String, Object>)saveMdEmlMngVoList.get(i), new MdEmlMngVo(), false);
}
二 日期工具集
package com.sds.faro.common.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import com.google.common.base.Strings;
import com.sds.faro.common.session.FaroUserSessionHolder;
public class DateUtil {
private DateUtil(){
}
/**
* Date?? ???? ? ????? ??? String??? ??? ?? ???
*
* @param date
* @return string (com.sds.faro.common.util.FaroConstants.DEFAULT_DATETIME_FORMAT ??)
*/
public static String getDateTimeString(final Date date) {
return getString(date, FaroConstants.DEFAULT_DATETIME_FORMAT);
}
/**
* Date?? ????? ??? String??? ??? ?? ???
*
* @param date
* @return string (com.sds.faro.common.util.FaroConstants.DEFAULT_DATE_FORMAT ??)
*/
public static String getDateString(final Date date) {
return getString(date, FaroConstants.DEFAULT_DATE_FORMAT);
}
public static String getString(final Date date, final String format){
if(date == null){
return null;
}
DateFormat dtFormat = new SimpleDateFormat(format);
dtFormat.setTimeZone(getTimeZone());
return dtFormat.format(date);
}
/**
* ???? String?? ?? Date? ?????
* ?? ??? ???? 0?? ??? ?? ???? ???
*
* @param dateString
* @return date (?? ??? 0?0?0?)
*/
public static Date getStartDate(final String dateString){
Calendar cal = getCalendar(dateString);
if(cal == null){
return null;
}
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* ???? String?? ?? Date? ?????
* ?? ??? 23?59?59??? ??? ?? ???? ???
* @param dateString
* @return date (?? ??? 23?59?59?)
*/
public static Date getEndDate(final String dateString){
Calendar cal = getCalendar(dateString);
if(cal == null){
return null;
}
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
return cal.getTime();
}
/**
* ???? ?? ??? String ?? ?? Date? ????? ???? ???
* @param datetimeString
* @return date
*/
public static Date getDate(final String datetimeString) {
final Calendar cal = getCalendar(datetimeString, FaroConstants.DEFAULT_DATETIME_FORMAT);
if (cal == null) {
return null;
}
return cal.getTime();
}
/**
* ???? ?? ??? String ?? ?? Date? ????? ???? ???
* 8 or 10 Byte???, (-, /)? ???? ????? Date? ????.
* jqxGrid? yyyy-MM-dd'T'HH:mm:ss.SSS'Z'?? ???? ???? TimeZone(GMT0) ???? Date? ????.
* @param datetimeString
* @return date
*/
public static Date getDateForJson(final String datetimeString) {
Calendar cal = null;
if(datetimeString.length()==8 || datetimeString.length()==10) {
cal = getCalendar(datetimeString.replaceAll("-", "").replaceAll("/", ""), "yyyyMMdd");
}
else {
cal = getCalendar(datetimeString, FaroConstants.DEFAULT_DATETIME_FORMAT_JSON);
}
if (cal == null) {
return null;
}
return cal.getTime();
}
private static Calendar getCalendar(final String dateString, final String format) {
if(Strings.isNullOrEmpty(dateString)){
return null;
}
TimeZone tz = getTimeZone();
// jqxGrid? DateWidget? ???? ?? GMT0? ??? ???? ???? ??
if(format.equals(FaroConstants.DEFAULT_DATETIME_FORMAT_JSON)) {
tz = TimeZone.getTimeZone("GMT0");
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(tz);
sdf.setLenient(false);
Date outputDate = null;
try {
outputDate = sdf.parse(dateString);
} catch (ParseException e) {
return null;
}
Calendar cal = Calendar.getInstance(tz);
cal.setTime(outputDate);
return cal;
}
private static Calendar getCalendar(final String dateString) {
return getCalendar(dateString, FaroConstants.DEFAULT_DATE_FORMAT);
}
private static TimeZone getTimeZone() {
if(FaroUserSessionHolder.getTimeZoneId()==null) {
return TimeZone.getDefault();
}
else {
return TimeZone.getTimeZone(FaroUserSessionHolder.getTimeZoneId());
}
}
public static void main(String args[]) {
String datetimeString = "2017-04-15T03:30:40.577Z";
System.out.println(TimeZone.getTimeZone(""));
System.out.println(TimeZone.getTimeZone("GMT0"));
System.out.println(TimeZone.getTimeZone("Asia/Shanghai"));
System.out.println(TimeZone.getTimeZone("UTC"));
System.out.println( DateUtil.getDateForJson(datetimeString) );
}
}
這個工具集可以處理yyyy-mm-dd的資料
如果查詢時只傳入沒有時間的日期資料,做搜尋條件,可能造成查詢的時候,結束日期只小於 yyyy-mm-dd 00:00:00 而實際想要的效果是
yyyy-MM-dd 23:59:59 這樣就可以用這個工具的函式自動給日期資料加上一天的最後一分鐘
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/750077/viewspace-2145340/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- java 常用工具類Java
- java 常用工具類 (值得收藏)Java
- java 常用工具類 方法整理Java
- Java常用工具類方法整理Java
- Java 常用工具類 Collections 原始碼分析Java原始碼
- 3.3 Java 中必須瞭解的常用類(常用工具類)Java
- Java單元測試常用工具類小結Java
- 技術乾貨:Java程式碼常用工具類整理歸納Java
- Java常用工具介紹Java
- 全網最全Flutter常用工具類Flutter
- Android常用工具類的封裝Android封裝
- 【web安全】程式設計常用工具類Web程式設計
- Java Web開發常用工具JavaWeb
- 專案開發必備,常用工具類
- java面試複習重點:類的管理及常用工具,教你抓住面試的重點!Java面試
- Javaweb常用工具類及配置檔案備份JavaWeb
- 類unix系統下常用工具及命令(轉)
- Java程式設計師常用工具集Java程式設計師
- commons-lang包常用工具類的基本使用
- Android快速開發系列 10個常用工具類Android
- 好程式設計師Java培訓幫你整理Java入門常用工具程式設計師Java
- Java常用類-Object類JavaObject
- JAVA常用類--Cleaner類Java
- 常用工具集
- lodash常用工具
- 前端常用工具前端
- window 常用工具
- 常用工具大全
- Java —— 列舉類(enum 類)Java
- Java —— 檔案類(File 類)Java
- Java —— 集合工具類(Collections 類)Java
- JAVA常用類--Runtime類Java
- Java超類與子類Java
- Java 抽象類Java抽象
- java 容器類Java
- Java 常用類Java
- 集合類【Java】Java
- 【java】Arrays類Java