Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 减少if-else以确定数据类型_Java - Fatal编程技术网

Java 减少if-else以确定数据类型

Java 减少if-else以确定数据类型,java,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(d

如何减少这种反射

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);
}

一、 我也想知道你为什么要这么做。但是,暂且不谈这一点,这里有一些未经测试的代码:

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);
List您可以使用和方法
getConstructor
(示例):


顺便说一句,它不适用于字符和布尔值,因为您对它们进行了特殊处理。

我认为您无法通过反射来减少代码量。首先,反射API非常冗长。第二,您在某些块中做的事情略有不同。特别是,Boolean的块不仅仅是调用构造函数。

谁在调用这个方法?为什么打电话的人不知道类型?
Object instance = Class.forName(dataType)
         .getConstructor(new Class[] {String.class})
         .newInstance(new Object[]{value});