java常用工具類

flzhang發表於2017-09-22

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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章