减少if else以确定dataType

时间:2012-06-05 10:27:27

标签: java

如何使用反射来减少这种情况

private static Object determineDataType(final String value, String dataType)
{
    System.out.println("Name--->>" + dataType);
    if(dataType.equals(Boolean.class.getName()))
    {
       return new Boolean(value);
    }
    else if(dataType.equals(String.class.getName()))
    {
        return new String(value);
    }
    else if(dataType.equals(Character.class.getName()))
    {
        return new String(value);
    }
    else if(dataType.equals(Byte.class.getName()))
    {
        return new Byte(value);
    }
    else if(dataType.equals(Short.class.getName()))
    {
        return new Short(value);
    }
    else if(dataType.equals(Integer.class.getName()))
    {
        return new Integer(value);
    }
    else if(dataType.equals(Long.class.getName()))
    {
        return new Long(value);
    }
    else if(dataType.equals(Float.class.getName()))
    {
        return  new Float(value);
    }
    else if(dataType.equals(Double.class.getName()))
    {
        return  new Double(value);
    }
    //defualt return the String value, Lets' AOPI do the Validation
    return new String(value);
}

3 个答案:

答案 0 :(得分:1)

我也想知道为什么世界上你会这样做。但是,暂时搁置一分钟,这里有一些未经测试的代码:

List<Class<?>> types = Arrays.asList(Long.class, Integer.class, ... );
for (Class<?> type : types) {
    if (type.getName().equals(dataType))
        return type.getConstructor(String.class).newInstance(value);
    // TODO: catch exceptions and probably re-throw wrapped
}
return new String(value);

答案 1 :(得分:1)

您可以使用Class.forName和方法getConstructorhere就是一个例子):

Object instance = Class.forName(dataType)
         .getConstructor(new Class[] {String.class})
         .newInstance(new Object[]{value});

顺便说一句,它不适用于Character和Boolean,因为你对它们进行了特殊的处理。

答案 2 :(得分:0)

我认为你不能在这里用反射来减少代码量。首先,反射API非常冗长。其次,你在某些块中做的事情略有不同。特别是,布尔的块不仅仅是调用构造函数。