Skip to content

Instantly share code, notes, and snippets.

@0532
Created September 29, 2014 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0532/c695aff3bdd777f6a422 to your computer and use it in GitHub Desktop.
Save 0532/c695aff3bdd777f6a422 to your computer and use it in GitHub Desktop.
对象操作辅助类
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