Commit f4038634 authored by yanzg's avatar yanzg

类型转换

parent e668000c
...@@ -405,7 +405,14 @@ public class ObjectHelper { ...@@ -405,7 +405,14 @@ public class ObjectHelper {
* @throws InstantiationException 异常信息 * @throws InstantiationException 异常信息
*/ */
public static <T> T convert(Class<T> toCls, Object from) throws IllegalAccessException, InstantiationException { public static <T> T convert(Class<T> toCls, Object from) throws IllegalAccessException, InstantiationException {
T to = toCls.newInstance(); if (from == null) {
return null;
}
T to = StringHelper.to(toCls, from);
if (to != null) {
return to;
}
to = toCls.newInstance();
writeWithToClass(to, from); writeWithToClass(to, from);
return to; return to;
} }
......
package com.yanzuoguang.util.helper; package com.yanzuoguang.util.helper;
import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.exception.CodeException; import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.exception.ExceptionHelper; import com.yanzuoguang.util.exception.ExceptionHelper;
...@@ -118,7 +119,7 @@ public class StringHelper { ...@@ -118,7 +119,7 @@ public class StringHelper {
if ( if (
(chars[start + 1] == 'x') || (chars[start + 1] == 'x') ||
(chars[start + 1] == 'X') (chars[start + 1] == 'X')
) { // leading 0x/0X ) { // leading 0x/0X
int i = start + 2; int i = start + 2;
if (i == sz) { if (i == sz) {
return false; // str == "0x" return false; // str == "0x"
...@@ -248,6 +249,9 @@ public class StringHelper { ...@@ -248,6 +249,9 @@ public class StringHelper {
* @return 返回获取的值 * @return 返回获取的值
*/ */
public static <T> T to(Class<T> cls, Object from) { public static <T> T to(Class<T> cls, Object from) {
if (from == null) {
return null;
}
String vName = cls.getName(); String vName = cls.getName();
Object to = null; Object to = null;
if (cls.isEnum()) { if (cls.isEnum()) {
...@@ -272,7 +276,10 @@ public class StringHelper { ...@@ -272,7 +276,10 @@ public class StringHelper {
if (to != null) { if (to != null) {
return (T) to; return (T) to;
} else { } else {
return (T) from; if (ObjectHelper.isSub(cls, from.getClass())) {
return (T) from;
}
return (T) to;
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment