检查Class <t>是否是原始的以及它的String,Number,Boolean,List或Map?</t>

时间:2014-04-20 06:39:49

标签: java

我有这个代码,我遇到了麻烦:

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 },NumberBooleanList

此代码可能有什么问题?

问题2:

如果修复了问题1,将Map分配给Object prop的最安全方法是什么,例如如果TT,那么它将是{{} 1}}对吗?如果它的原语如StringString.valueOfint

,该怎么办?

1 个答案:

答案 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;
}