[英]Instantiating class from name with parameterized types in constructor
Is it somehow possible to create object from name with constructor parameters as parametrized types. 是否可以用构造函数参数作为参数化类型从名称创建对象。 I doubt because in runtime types are erasured.
我怀疑,因为在运行时类型被擦除。 Are there some workarounds for similar problems?
有类似问题的解决方法吗?
Basically my scenario is like this: 基本上我的情况是这样的:
Abstract generic: 抽象泛型:
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;
}
}
Implementation: 执行:
public class Amount extends Parameter<Double> {
public Amount(Double minValue, Double maxValue) {
super(minValue, maxValue);
}
}
Parameter from name: 名称中的参数:
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
}
I can't use normal json serialization/deserialization as I am using jsondb and because it has some limitations with storing list of different objects by interface type I need to save it via it's annotated document class (ParameterJson) and restore earlier object based on record's name. 我不能像使用jsondb那样使用普通的json序列化/反序列化,并且由于按接口类型存储不同对象的列表存在一些限制,我需要通过带注释的文档类(ParameterJson)保存它,并根据记录的内容恢复早期的对象名称。
If you already have extracted minValue & maxValue objects, these should be of the type you want, and can just use: 如果您已经提取了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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.