是否有可能以构造函数参数作为参数化类型从名称创建对象。我怀疑是因为在运行时类型被擦除了。是否有针对类似问题的解决方法?
基本上我的场景是这样的:
抽象泛型:
public abstract class Parameter<T> {
private String parameterName = this.getClass().getName();
private T minValue;
private T maxValue;
public ParameterJson<T> toJson() {
ParameterJson<T> result = new ParameterJson<>();
result.setName(this.parameterName);
result.setMinValue(this.minValue);
result.setMaxValue(this.maxValue);
return result;
}
}
执行:
public class Amount extends Parameter<Double> {
public Amount(Double minValue, Double maxValue) {
super(minValue, maxValue);
}
}
名称中的参数:
public class ParameterJson<T> implements Serializable {
private String name;
private T minValue;
private T maxValue;
public Parameter<T> toObject() {
Object object = null;
try {
Class<Parameter<T>> clazz = (Class<Parameter<T>>) Class.forName(this.name); //unchecked cast
Constructor<?> cons = clazz.getConstructor(Double.class, Double.class);
object = cons.newInstance(this.minValue, this.maxValue); // it works because for now I have only this case but is not typesafe
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return (Parameter<T>) object; ////unchecked cast
}
我不能使用普通的 json 序列化/反序列化,因为我正在使用 jsondb,因为它在按接口类型存储不同对象的列表方面存在一些限制,我需要通过它的带注释的文档类 (ParameterJson) 保存它并根据记录恢复早期的对象姓名。