Created
September 29, 2014 08:23
-
-
Save 0532/c695aff3bdd777f6a422 to your computer and use it in GitHub Desktop.
对象操作辅助类
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pub.tools; | |
import org.springframework.util.StringUtils; | |
import java.lang.reflect.Field; | |
import java.math.BigDecimal; | |
/** | |
* 对象操作辅助类 | |
*/ | |
public class BeanHelper { | |
/** | |
* Field Type: BigDecimal and String only | |
* | |
* @param src source Object | |
* @param des destination Object | |
* @throws IllegalAccessException | |
*/ | |
public static void copyFields(Object src, Object des) throws IllegalAccessException { | |
Field[] srcFields = src.getClass().getDeclaredFields(); | |
for (Field field : srcFields) { | |
field.setAccessible(true); | |
Object fieldValue = field.get(src); | |
Field desField = null; | |
try { | |
desField = des.getClass().getDeclaredField(field.getName()); | |
} catch (NoSuchFieldException e) { | |
try { | |
desField = des.getClass().getDeclaredField(field.getName().toUpperCase()); | |
} catch (NoSuchFieldException e1) { | |
try { | |
desField = des.getClass().getDeclaredField(field.getName().toLowerCase()); | |
} catch (NoSuchFieldException e2) { | |
continue; | |
} | |
} | |
} | |
desField.setAccessible(true); | |
String desFieldTypeName = desField.getType().getSimpleName(); | |
if (desFieldTypeName.equals("String")) { | |
if (fieldValue != null) { | |
desField.set(des, StringUtils.isEmpty(fieldValue) ? "" : fieldValue.toString()); | |
} else { | |
desField.set(des, ""); | |
} | |
} else if (desFieldTypeName.equals("BigDecimal")) { | |
if (fieldValue != null) desField.set(des, new BigDecimal(fieldValue.toString())); | |
} else { | |
throw new RuntimeException("desFieldInstance : unsupported field type[BigDecimal and String only]."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment