[英]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.