重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

java常用工具类有哪些

这篇文章给大家分享的是有关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 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 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 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 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 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 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 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 reqParam 传过来的参数
List> saveMdEmlMngVoList = (List>) reqParam.get("reqListData");
for(int i=0; saveMdEmlMngVoList!=null && i MdEmlMngVo saveVo = (MdEmlMngVo)VoUtil.convertMapToObject((Map)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 这样就可以用这个工具的函数自动给日期数据加上一天的最后一分钟

感谢各位的阅读!关于“java常用工具类有哪些”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


网站名称:java常用工具类有哪些
文章出自:http://cqcxhl.cn/article/gspcig.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP