我有这个代码,我遇到了麻烦:
public static <T> T createPOJOFrom(Class<T> clazz, Entity source){
T obj = null;
if (clazz.isPrimitive()){
Map<String,Object> props = source.getProperties();
Iterator<Map.Entry<String,Object>> it = props.entrySet().iterator();
Object prop = it.next();
obj = (T) prop; // FIXME this can be dangerous!
} else {
obj = createPOJOFrom(clazz, createMapFromEntity(source));
}
return obj;
}
问题1:
问题是clazz.isPrimitive
返回false
,因为我可以在调试控制台中看到clazz = class java.lang.String
,现在我如何检查String
,{{1 },Number
,Boolean
和List
?
此代码可能有什么问题?
问题2:
如果修复了问题1,将Map
分配给Object prop
的最安全方法是什么,例如如果T
是T
,那么它将是{{} 1}}对吗?如果它的原语如String
,String.valueOf
,int
?
答案 0 :(得分:0)
这是最后一眼:
public static <T> T createObjectFrom(Class<T> clazz, Entity source){
T obj = null;
Map<String,Object> props = source.getProperties();
Iterator<Map.Entry<String,Object>> it = props.entrySet().iterator();
if (props.size() > 1){
if (clazz == List.class){
throw new RuntimeException("Not yet implemented");
} else if (clazz == Map.class){
throw new RuntimeException("Not yet implemented");
} else {
obj = createPOJOFrom(clazz, createMapFromEntity(source));
}
} else if (props.size() == 1) {
Map.Entry<String,Object> entry = it.next();
Object value = entry.getValue();
if (clazz.isPrimitive()){
obj = (T) value;
} else if (clazz == String.class){
String prop = String.valueOf(value);
obj = (T) prop;
} else if (clazz == Number.class || clazz == Long.class || clazz == Integer.class){
Long prop = Long.valueOf(String.valueOf(value));
obj = (T) prop;
} else if (clazz == Boolean.class){
Boolean prop = Boolean.valueOf(String.valueOf(value));
obj = (T) prop;
}
} else {
// empty
}
return obj;
}