java - 在构造函数中使用参数化类型从名称实例化类
问题描述
是否有可能以构造函数参数作为参数化类型从名称创建对象。我怀疑是因为在运行时类型被擦除了。是否有针对类似问题的解决方法?
基本上我的场景是这样的:
抽象泛型:
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) 保存它并根据记录恢复早期的对象姓名。
解决方案
如果您已经提取了 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);
推荐阅读
- angular - “cors header 'access-control-allow-origin' missing” 拒绝请求,即使来源是允许的
- php - 结束 TCP/IP 流所需的奇怪字符无法弄清楚它是什么
- excel-2016 - 在满足一个条件的行中,计算 5 个最大的行中有多少也满足另一个条件
- python - 提取向上指向的车道线
- azure-stream-analytics - Azure 流分析查询 - 获取所有设备的最后一个请求
- c# - 传递给 PushStreamContent 的 Action 是否保证被调用?
- php - PHP删除重复键并将值组合到多维数组中
- javascript - 数组数组中对象的总和值
- java - 从 Android 应用程序到 Python Flask 中的 Web 服务的 HTTP 发布
- javascript - 如何从字典中的数组中调用随机值?(不和谐机器人)