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;
...@@ -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,8 +276,11 @@ public class StringHelper { ...@@ -272,8 +276,11 @@ public class StringHelper {
if (to != null) { if (to != null) {
return (T) to; return (T) to;
} else { } else {
if (ObjectHelper.isSub(cls, from.getClass())) {
return (T) from; 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