繁体   English   中英

在构造函数中使用参数化类型从名称实例化类

[英]Instantiating class from name with parameterized types in constructor

是否可以用构造函数参数作为参数化类型从名称创建对象。 我怀疑,因为在运行时类型被擦除。 有类似问题的解决方法吗?

基本上我的情况是这样的:

抽象泛型:

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
    }

我不能像使用jsondb那样使用普通的json序列化/反序列化,并且由于按接口类型存储不同对象的列表存在一些限制,我需要通过带注释的文档类(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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM