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 这样就可以用这个工具的函数自动给日期数据加上一天的最后一分钟

时间: 2024-10-25 17:32:52

java常用工具类的相关文章

java常用工具类之Excel操作类及依赖包下载_java

依赖包下载:http://xiazai.jb51.net/201407/tools/java-excel-dependency(jb51.net).rar Excel工具类ExcelUtil.java源码: package com.itjh.javaUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStr

java常用工具类之DES和Base64加密解密类_java

一.DES加密和解密 package com.itjh.javaUtil; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecExc

PHP常用工具类大全附全部代码下载_php实例

废话不多说了,直接给大家贴php代码了,具体代码如下所示: <?php /** * 助手类 * @author www.shouce.ren * */ class Helper { /** * 判断当前服务器系统 * @return string */ public static function getOS(){ if(PATH_SEPARATOR == ':'){ return 'Linux'; }else{ return 'Windows'; } } /** * 当前微妙数 * @retu

关于Java常用工具您不知道的5件事

Java 常用工具,如解析.计时和声音 很多年前,当我还是高中生的时候,我曾考虑以小说作家作为我的职业追求,我订阅了一本 Writer's Digest 杂志.我记得其中有篇专 栏文章,是关于 "太小而难以保存的线头",专栏作者描述厨房储物抽屉中放满了无法分类的玩意儿.这句话我一直铭记在心,它正好用 来描述本文的内容,本系列的最后一篇(至少目前是这样). Java 平台就充满了这样的 "线头" - 有用的命令行工具和库,大多数 Java 开发人员甚至都不知道,更别提

IOS开发--常用工具类收集整理(Objective-C)(持续更新)

 前言:整理和收集了IOS项目开发常用的工具类,最后也给出了源码下载链接. 这些可复用的工具,一定会给你实际项目开发工作锦上添花,会给你带来大大的工作效率. 重复造轮子的事情,除却自我多练习编码之外,就不要傻傻的重复造轮子了,还是提高工作效率,早点完成工作早点回家陪老婆孩子. 所以下面备份的常用工具类一定是你需要的. 前提:你有一定的开发经验,知道它们在开发的什么地方需要,你都不知道用在哪里,那你需要个毛啊,还是好好另外学好基础吧.少儿不宜,请离开哦. 插件目录列表:(持续更新和添加) 1.UI

C#常用工具类——Excel操作类

/// 常用工具类--Excel操作类 /// <para> ------------------------------------------------</para> /// <para> CreateConnection:根据Excel文件路径和EXCEL驱动版本生成OleConnection对象实例</para> /// <para> ExecuteDataSet:执行一条SQL语句,返回一个DataSet对象</para>

[C#] 常用工具类——加密解密类

using System; using System.Configuration; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using S

[C#] 常用工具类——系统日志类

using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Utils { /// <summary> /// <para> </para> /// 常用工具类--系统日志类 /// <para> ---------------------------------------------------</par

[C#] 常用工具类——直接在浏览器输出数据

/// <summary> /// <para> </para> /// 常用工具类--直接在浏览器输出数据 /// <para> -------------------------------------------------------------</para> /// <para> DumpDataTable:接在浏览器输出数据DataTable</para> /// <para> DumpListIt