package org.sakaiproject.util;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale; /**
* 类型转换辅助工具类<br>
*
*/
public class TypeCaseHelper { /**
* 转换核心实现方法
*
* @param obj
* @param type
* @param format
* @return Object
* @throws TypeCastException
*/
public static Object convert(Object obj, String type, String format) throws TypeCastException {
Locale locale = new Locale("zh", "CN", "");
if (obj == null)
return null;
if (obj.getClass().getName().equals(type))
return obj;
if ("Object".equals(type) || "java.lang.Object".equals(type))
return obj;
String fromType = null;
if (obj instanceof String) {
fromType = "String";
String str = (String) obj;
if ("String".equals(type) || "java.lang.String".equals(type))
return obj;
if (str.length() == 0)
return null;
if ("Boolean".equals(type) || "java.lang.Boolean".equals(type)) {
Boolean value = null;
if (str.equalsIgnoreCase("TRUE"))
value = new Boolean(true);
else
value = new Boolean(false);
return value;
}
if ("Double".equals(type) || "java.lang.Double".equals(type))
try {
Number tempNum = getNf(locale).parse(str);
return new Double(tempNum.doubleValue());
} catch (ParseException e) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
if ("BigDecimal".equals(type) || "java.math.BigDecimal".equals(type))
try {
BigDecimal retBig = new BigDecimal(str);
int iscale = str.indexOf(".");
int keylen = str.length();
if (iscale > -1) {
iscale = keylen - (iscale + 1);
return retBig.setScale(iscale, 5);
} else {
return retBig.setScale(0, 5);
}
} catch (Exception e) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
if ("Float".equals(type) || "java.lang.Float".equals(type))
try {
Number tempNum = getNf(locale).parse(str);
return new Float(tempNum.floatValue());
} catch (ParseException e) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
if ("Long".equals(type) || "java.lang.Long".equals(type))
try {
NumberFormat nf = getNf(locale);
nf.setMaximumFractionDigits(0);
Number tempNum = nf.parse(str);
return new Long(tempNum.longValue());
} catch (ParseException e) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
if ("Integer".equals(type) || "java.lang.Integer".equals(type))
try {
NumberFormat nf = getNf(locale);
nf.setMaximumFractionDigits(0);
Number tempNum = nf.parse(str);
return new Integer(tempNum.intValue());
} catch (ParseException e) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
if ("Date".equals(type) || "java.sql.Date".equals(type)) {
if (format == null || format.length() == 0)
try {
return Date.valueOf(str);
} catch (Exception e) {
try {
DateFormat df = null;
if (locale != null)
df = DateFormat.getDateInstance(3, locale);
else
df = DateFormat.getDateInstance(3);
java.util.Date fieldDate = df.parse(str);
return new Date(fieldDate.getTime());
} catch (ParseException e1) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
}
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
java.util.Date fieldDate = sdf.parse(str);
return new Date(fieldDate.getTime());
} catch (ParseException e) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
}
if ("Timestamp".equals(type) || "java.sql.Timestamp".equals(type)) {
if (str.length() == 10)
str = str + " 00:00:00";
if (format == null || format.length() == 0)
try {
return Timestamp.valueOf(str);
} catch (Exception e) {
try {
DateFormat df = null;
if (locale != null)
df = DateFormat.getDateTimeInstance(3, 3, locale);
else
df = DateFormat.getDateTimeInstance(3, 3);
java.util.Date fieldDate = df.parse(str);
return new Timestamp(fieldDate.getTime());
} catch (ParseException e1) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
}
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
java.util.Date fieldDate = sdf.parse(str);
return new Timestamp(fieldDate.getTime());
} catch (ParseException e) {
throw new TypeCastException("Could not convert " + str + " to " + type + ": ", e);
}
} else {
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
}
if (obj instanceof BigDecimal) {
fromType = "BigDecimal";
BigDecimal bigD = (BigDecimal) obj;
if ("String".equals(type))
return getNf(locale).format(bigD.doubleValue());
if ("BigDecimal".equals(type) || "java.math.BigDecimal".equals(type))
return obj;
if ("Double".equals(type))
return new Double(bigD.doubleValue());
if ("Float".equals(type))
return new Float(bigD.floatValue());
if ("Long".equals(type))
return new Long(Math.round(bigD.doubleValue()));
if ("Integer".equals(type))
return new Integer((int) Math.round(bigD.doubleValue()));
else
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
if (obj instanceof Double) {
fromType = "Double";
Double dbl = (Double) obj;
if ("String".equals(type) || "java.lang.String".equals(type))
return getNf(locale).format(dbl.doubleValue());
if ("Double".equals(type) || "java.lang.Double".equals(type))
return obj;
if ("Float".equals(type) || "java.lang.Float".equals(type))
return new Float(dbl.floatValue());
if ("Long".equals(type) || "java.lang.Long".equals(type))
return new Long(Math.round(dbl.doubleValue()));
if ("Integer".equals(type) || "java.lang.Integer".equals(type))
return new Integer((int) Math.round(dbl.doubleValue()));
if ("BigDecimal".equals(type) || "java.math.BigDecimal".equals(type))
return new BigDecimal(dbl.toString());
else
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
if (obj instanceof Float) {
fromType = "Float";
Float flt = (Float) obj;
if ("String".equals(type))
return getNf(locale).format(flt.doubleValue());
if ("BigDecimal".equals(type) || "java.math.BigDecimal".equals(type))
return new BigDecimal(flt.doubleValue());
if ("Double".equals(type))
return new Double(flt.doubleValue());
if ("Float".equals(type))
return obj;
if ("Long".equals(type))
return new Long(Math.round(flt.doubleValue()));
if ("Integer".equals(type))
return new Integer((int) Math.round(flt.doubleValue()));
else
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
if (obj instanceof Long) {
fromType = "Long";
Long lng = (Long) obj;
if ("String".equals(type) || "java.lang.String".equals(type))
return getNf(locale).format(lng.longValue());
if ("Double".equals(type) || "java.lang.Double".equals(type))
return new Double(lng.doubleValue());
if ("Float".equals(type) || "java.lang.Float".equals(type))
return new Float(lng.floatValue());
if ("BigDecimal".equals(type) || "java.math.BigDecimal".equals(type))
return new BigDecimal(lng.toString());
if ("Long".equals(type) || "java.lang.Long".equals(type))
return obj;
if ("Integer".equals(type) || "java.lang.Integer".equals(type))
return new Integer(lng.intValue());
else
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
if (obj instanceof Integer) {
fromType = "Integer";
Integer intgr = (Integer) obj;
if ("String".equals(type) || "java.lang.String".equals(type))
return getNf(locale).format(intgr.longValue());
if ("Double".equals(type) || "java.lang.Double".equals(type))
return new Double(intgr.doubleValue());
if ("Float".equals(type) || "java.lang.Float".equals(type))
return new Float(intgr.floatValue());
if ("BigDecimal".equals(type) || "java.math.BigDecimal".equals(type)) {
String str = intgr.toString();
BigDecimal retBig = new BigDecimal(intgr.doubleValue());
int iscale = str.indexOf(".");
int keylen = str.length();
if (iscale > -1) {
iscale = keylen - (iscale + 1);
return retBig.setScale(iscale, 5);
} else {
return retBig.setScale(0, 5);
}
}
if ("Long".equals(type) || "java.lang.Long".equals(type))
return new Long(intgr.longValue());
if ("Integer".equals(type) || "java.lang.Integer".equals(type))
return obj;
else
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
if (obj instanceof Date) {
fromType = "Date";
Date dte = (Date) obj;
if ("String".equals(type) || "java.lang.String".equals(type))
if (format == null || format.length() == 0) {
return dte.toString();
} else {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new java.util.Date(dte.getTime()));
}
if ("Date".equals(type) || "java.sql.Date".equals(type))
return obj;
if ("Time".equals(type) || "java.sql.Time".equals(type))
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
if ("Timestamp".equals(type) || "java.sql.Timestamp".equals(type))
return new Timestamp(dte.getTime());
else
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
if (obj instanceof Timestamp) {
fromType = "Timestamp";
Timestamp tme = (Timestamp) obj;
if ("String".equals(type) || "java.lang.String".equals(type))
if (format == null || format.length() == 0) {
return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(tme).toString();
} else {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new java.util.Date(tme.getTime()));
}
if ("Date".equals(type) || "java.sql.Date".equals(type))
return new Date(tme.getTime());
if ("Time".equals(type) || "java.sql.Time".equals(type))
return new Time(tme.getTime());
if ("Timestamp".equals(type) || "java.sql.Timestamp".equals(type))
return obj;
else
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
if (obj instanceof Boolean) {
fromType = "Boolean";
Boolean bol = (Boolean) obj;
if ("Boolean".equals(type) || "java.lang.Boolean".equals(type))
return bol;
if ("String".equals(type) || "java.lang.String".equals(type))
return bol.toString();
if ("Integer".equals(type) || "java.lang.Integer".equals(type)) {
if (bol.booleanValue())
return new Integer(1);
else
return new Integer(0);
} else {
throw new TypeCastException("Conversion from " + fromType + " to " + type + " not currently supported");
}
}
if ("String".equals(type) || "java.lang.String".equals(type))
return obj.toString();
else
throw new TypeCastException("Conversion from " + obj.getClass().getName() + " to " + type + " not currently supported");
} private static NumberFormat getNf(Locale locale) {
NumberFormat nf = null;
if (locale == null)
nf = NumberFormat.getNumberInstance();
else
nf = NumberFormat.getNumberInstance(locale);
nf.setGroupingUsed(false);
return nf;
} public static Boolean convert2SBoolean(Object obj) throws TypeCastException {
return (Boolean) convert(obj, "Boolean", null);
} public static Integer convert2Integer(Object obj) throws TypeCastException {
return (Integer) convert(obj, "Integer", null);
} public static String convert2String(Object obj) throws TypeCastException {
return (String) convert(obj, "String", null);
} public static String convert2String(Object obj, String defaultValue) throws TypeCastException {
Object s = convert(obj, "String", null);
if (s != null)
return (String) s;
else
return "";
} public static Long convert2Long(Object obj) throws TypeCastException {
return (Long) convert(obj, "Long", null);
} public static Double convert2Double(Object obj) throws TypeCastException {
return (Double) convert(obj, "Double", null);
} public static BigDecimal convert2BigDecimal(Object obj, int scale) throws TypeCastException {
return ((BigDecimal) convert(obj, "BigDecimal", null)).setScale(scale, 5);
} public static Date convert2SqlDate(Object obj, String format) throws TypeCastException {
return (Date) convert(obj, "Date", format);
} public static Timestamp convert2Timestamp(Object obj, String format) throws TypeCastException {
return (Timestamp) convert(obj, "Timestamp", format);
}
}

类型转换辅助工具类TypeCaseHelper的更多相关文章

  1. java在文本处理中的相关辅助工具类

    1,java分词 package com.bobo.util; import ICTCLAS.I3S.AC.ICTCLAS50; public class Cutwords { public stat ...

  2. JUC——线程同步辅助工具类(Semaphore,CountDownLatch,CyclicBarrier)

    锁的机制从整体的运行转态来讲核心就是:阻塞,解除阻塞,但是如果仅仅是这点功能,那么JUC并不能称为一个优秀的线程开发框架,然而是因为在juc里面提供了大量方便的同步工具辅助类. Semaphore信号 ...

  3. JUC——线程同步辅助工具类(Exchanger,CompletableFuture)

    Exchanger交换空间 如果现在有两个线程,一个线程负责生产数据,另外一个线程负责消费数据,那么这个两个线程之间一定会存在一个公共的区域,那么这个区域的实现在JUC包之中称为Exchanger. ...

  4. 制作ado开发辅助工具类SqlHelper

    public static class SqlHelper { //通过配置文件获取连接字符创 private static readonly string constr = Configuratio ...

  5. Web层辅助工具类

    Java web开发中经常用到的一些方法: import java.io.BufferedReader; import java.net.InetAddress; import java.net.Un ...

  6. 好用的Cache辅助工具类

    话不多说,直接上代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; usi ...

  7. Redis源代码分析(二十四)--- tool工具类(2)

    在上篇文章中初步的分析了一下,Redis工具类文件里的一些使用方法,包含2个随机算法和循环冗余校验算法,今天,继续学习Redis中的其它的一些辅助工具类的使用方法.包含里面的大小端转换算法,sha算法 ...

  8. [19/03/27-星期三] 容器_Iterator(迭代器)之遍历容器元素(List/Set/Map)&Collections工具类

    一.概念 迭代器为我们提供了统一的遍历容器的方式 /* *迭代器遍历 * */ package cn.sxt.collection; import java.security.KeyStore.Ent ...

  9. JUC 常用4大并发工具类

    什么是JUC? JUC就是java.util.concurrent包,这个包俗称JUC,里面都是解决并发问题的一些东西 该包的位置位于java下面的rt.jar包下面 4大常用并发工具类: Count ...

随机推荐

  1. webapp中fixed问题解决方案

    主要问题: 1,头部输入框固定后,只要再滑动内容的话,输入框会随着滑动内容而滑动. 2,在低端机:2.3以下的安卓机,你会发现怎么解决都不行的,系统浏览器是不会支持的,头部底部固定的话会滑动内容而滑动 ...

  2. 黑客攻防技术宝典Web实战篇(三)web攻击方式总结

    web攻击的手段无非就是使服务器资源耗尽,使服务器无法接收正常请求. 一.DDos攻击 二.DRDos攻击 三.慢攻击 与Ddos攻击相反,慢攻击并不是以多取胜,而是靠保持连接.

  3. 【Bootstrap】Bootstrap和Java分页-第一篇

    目录 关于此文 pagination BetweenIndex DefaultPagination QueryHandler BookDaoImpl BookServiceImpl BookActio ...

  4. Vno博客样式分享

    不知不觉有一年多没有更新博客了,还是几位园友因为喜欢这套博客样式发了消息,否则我都快忘记自己还有一个博客了,哈哈. 言归正传,这套博客样式是当时闲来无事copy的iOS界喵神的博客Vno,确实很漂亮, ...

  5. 3_mysql 主从复制

    mysql 主从复制 网易数据库 石勇 提纲 什么是主从复制 主从复制的原理 主从复制的用途 主从复制的搭建 主从复制的问题 什么是主从复制 数据拷贝 准实时 源-主节点:目的-从节点 主从复制的原理 ...

  6. USB协议[转]_基本上涵盖了所有最基础的USB协议相关知识。

    背景: 需要使用到USB协议,我一直尝试着去强记这个流程,现在看来,其实不用.看多了,把这个过程具象出来,就牢牢记住了. 正文: 正文转自:http://fangjian0518.blog.163.c ...

  7. bootstrap-collapse

    colapse插件:折叠功能 插件:collapse.js 实现方法:以data-toggle做被点击者,以div class="collapse in"显示展开内容 <sc ...

  8. http://debugjs.com/

    浏览器内调试js代码,这篇文章介绍了作者的开发心路 http://amasad.me/2014/01/06/building-an-in-browser-javascript-vm-and-debug ...

  9. linux shell脚本常用语句

    linux shell 指令 诸如-d, -f, -e之类的判断表达式: 文件比较运算符-e filename  如果 filename存在,则为真  [ -e /var/log/syslog ]-d ...

  10. 将Apache加入到linux系统service

    将Apache加入到linux系统service 将apache加入到linux系统服务,用service命令来控制apache的启动和停止. 本文由乌合之众瞎写http://www.cnblogs. ...