java常用工具类有哪些

发布时间:2021-12-30 16:11:46 作者:小新
来源:亿速云 阅读:109

这篇文章给大家分享的是有关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 这样就可以用这个工具的函数自动给日期数据加上一天的最后一分钟

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

推荐阅读:
  1. java 常用工具类
  2. javascript常用工具类如何封装

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:CRM中间件里的订阅者模式怎么实现

下一篇:怎么阻止SAP CRM自动被置为传输状态的行为

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》