使用 Field.set() 不会更改数据类型以适应字段类型。如果要设置多种类型,则必须先进行转换。例如
Field field = thObject.getClass().getDeclaredField(n.getNodeName());
field.setAccessible(true);
Object value = n.getNodeValue();
Object asType = convertToType(value, field.getType());
field.set(thObject, asType);
您必须实现 convertToType 以满足您的需求。
这是一个简单的实现。
private static final Map<Class, Class> WRAPPER_MAP = new LinkedHashMap<Class, Class>() {{
put(boolean.class, Boolean.class);
put(byte.class, Byte.class);
put(char.class, Character.class);
put(short.class, Short.class);
put(int.class, Integer.class);
put(float.class, Float.class);
put(long.class, Long.class);
put(double.class, Double.class);
}};
public static <T> T convertToType(Object o, Class<T> clazz) {
Class<T> wrapper = WRAPPER_MAP.get(clazz);
if (wrapper != null)
clazz = wrapper;
if (o == null || clazz.isInstance(o))
return (T) o;
try {
try {
Method valueOf = clazz.getDeclaredMethod("valueOf", o.getClass());
return (T) valueOf.invoke(null, o);
} catch (NoSuchMethodException e1) {
Constructor<T> constructor = clazz.getConstructor(o.getClass());
return constructor.newInstance(o);
}
} catch (Exception e) {
throw new AssertionError(e);
}
}
public static void main(String... args) {
String text = "1000";
for (Class clazz : new Class[]{String.class, Integer.class, double.class, BigDecimal.class, Thread.class}) {
Object o = convertToType(text, clazz);
System.out.println(o.getClass() + " " + o);
}
Object o = convertToType("RUNNABLE", Thread.State.class);
System.out.println(o.getClass() + " " + o);
String dateString = new Date().toString();
Date date = convertToType(dateString, Date.class);
System.out.println(date.getClass() + " " + date);
}
印刷
class java.lang.String 1000
class java.lang.Integer 1000
class java.lang.Double 1000.0
class java.math.BigDecimal 1000
class java.lang.Thread Thread[1000,5,main]
class java.lang.Thread$State RUNNABLE
class java.util.Date Thu Jan 03 17:08:50 GMT 2013
日期字符串必须是Date 将解析的格式,或者您可以使用 SimpleDateFormat 来使用您选择的格式。