首页 > 解决方案 > 在构造函数中使用参数化类型从名称实例化类

问题描述

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

基本上我的场景是这样的:

抽象泛型:

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) 保存它并根据记录恢复早期的对象姓名。

标签: javagenericsreflectionconstructor

解决方案


如果您已经提取了 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);

推荐阅读