ssukienn
ssukienn

Reputation: 588

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.

Upvotes: 0

Views: 57

Answers (1)

AJNeufeld
AJNeufeld

Reputation: 8695

If you already have extracted minValue & maxValue objects, these should be of the type you want, and can just use:

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);

Upvotes: 1

Related Questions