有没有可能用构造函数参数从名称创建对象作为参数化类型。我对此表示怀疑,因为在运行时类型会被擦除。对于类似的问题,有什么变通办法吗?
基本上我的场景是这样的:
抽象泛型:
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)保存它,并根据记录的名称恢复早期的对象。
发布于 2018-06-05 05:18:56
如果您已经提取了minValue和maxValue对象,这些对象应该是您想要的类型,并且只需使用:
Class<Parameter<T>> clazz = (Class<Parameter<T>>) Class.forName(this.name); //unchecked cast
Constructor<?> cons = clazz.getConstructor(minValue.getClass(), maxValue.getClass());
object = cons.newInstance(minValue, maxValue);
https://stackoverflow.com/questions/50686975
复制相似问题