0

如果我想询问原始类型名称,我想知道使用什么首选方法。我需要创建一个枚举类还是使用已经存在的一个(我搜索这个没有成功)

在这种情况下你有什么建议?

这是我的代码:

     else if (typeName.equals("char")) {
                return new SwitchInputType<Character>(new Character('z'));
            } else if (typeName.equals("decimal")
                    || (typeName.equals("java.math.BigDecimal"))) { 
...
4

2 回答 2

1

您可以将变量转换为Object,然后Class像这样获取该对象的:

else if (((Object) typeName).getClass() == Character.class) {  
          return new SwitchInputType<Character>(new Character('z'));
}   
else if (typeName != null && ((Object) typeName).getClass() == BigDecimal.class) { 

}
于 2013-02-17T09:57:29.577 回答
0

我不喜欢有很多 if-else 的代码。所以,这是我对同样问题的解决方案。

枚举类型:

public enum Types {
    BYTE,
    BOOLEAN,
    SHORT,
    CHAR,
    INT,
    FLOAT,
    LONG,
    DOUBLE,
    OBJECT;

    private static final String ALL_TYPES_STRING = Arrays.toString(Types.values());

    public static Types getType(Class<?> clazz) {
        String className = clazz.getSimpleName().toUpperCase();
        if (ALL_TYPES_STRING.contains(className)) {
            return Types.valueOf(className);
        } else {
            return Types.OBJECT;
        }
    }
}

ReflectionHelper 的方法:

 public static void setFieldValue(Object object,
                                     String fieldName,
                                     String value) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);

            Types types = Types.getType(field.getType());
            switch (types) {
                case BYTE:
                    field.set(object, Byte.valueOf(value));
                    break;
                case BOOLEAN:
                    field.set(object, Boolean.valueOf(value));
                    break;
                case SHORT:
                    field.set(object, Short.valueOf(value));
                    break;
                case CHAR:
                    field.set(object, value.charAt(0));
                    break;
                case INT:
                    field.set(object, Integer.decode(value));
                    break;
                case FLOAT:
                    field.set(object, Float.valueOf(value));
                    break;
                case LONG:
                    field.set(object, Long.valueOf(value));
                    break;
                case DOUBLE:
                    field.set(object, Double.valueOf(value));
                    break;
                case OBJECT:
                default:
                    field.set(object, value);
            }

            field.setAccessible(false);
        } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
于 2015-08-04T16:42:16.210 回答