如何将值解析为适当的目标类型

时间:2019-03-06 22:12:08

标签: java object

我有一个方法,它有两个参数值:Object和initialValueType:String。

public Object parseValueForInitialValueType(Object value, String initialValueType) {
    Class<?> clazz = Class.forName(initialValueType);
    Constructor<?> constructor = clazz.getConstructor(String.class);
    return constructor.newInstance(value);
}

此参数可能具有以下值:

value -> "test":String; initialValueType -> "java.lang.String"; method output -> "test":String
value -> 123.0:Double; initialValueType -> "java.lang.Double"; method output -> 123.0:Double
value -> "456.0":String; initialValueType -> "java.lang.Double"; method output -> "426.0:Double
value -> "123.000":String; initialValueType -> "java.math.BigDecimal"; method output -> 123.000:BigDecimal

问题是,我得到异常:

Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

如何将值解析为所需的initialValueType?

基本上,我想为initialValueType构造一个新对象。

1 个答案:

答案 0 :(得分:0)

似乎是解决方案:

public Object parseValueForInitialValueType(Object value, String initialValueType) {
    Class<?> clazz = Class.forName(initialValueType);
    Constructor<?> constructor = clazz.getConstructor(String.class);
    return constructor.newInstance(String.valueOf(value));
}