[英]Instantiate Parameterized Type class with Class<?> variable
(注意:我在類似的領域中搜索了關於SO的多個問題,但從未遇到針對我的想法的答案)。
考慮一下我是否有一個類或枚舉Foo
,其中每個實例都有一個Class<?> type
字段:
public enum Foo {
A (Integer.class), B (Double.class), C (String.class);
public final Class<?> type;
Foo(Class<?> type) {
this.type = type;
}
}
然后我有一個通用類Bar<V>
:
public class Bar<V> {
private V value;
// default constructor
public Bar() {}
// getter
public V getValue(){
return value;
}
// setter
public void setValue(V value){
this.value = value;
}
}
是否可以從給定Foo
的Class<?> type
字段中使用類型實例化Bar
的實例,而無需了解Foo.type
的特定類型? 例如,我可以通過靜態方法或某種工廠方法來調用它。
編輯:
要指定Bar的功能:Bar用一個簡單的getter / setter環繞一個值,並具有一致的接口,但類型未知。 我的想法的好處是基於Foo實例創建Bar實例。 例如,使用Foo.A.type
值(為Integer.class
)來實例化Bar<Integer>
而無需提前知道Foo.A.type
的值為Integer.class
。
給定Bar
類中的構造函數,要實例化一個新的Bar<V>
對象,您需要一個V
類型的對象。
因此,您的問題轉化為實例化類型為Class<V>
的對象。 更具體地說,假設Foo
類中已有一個Foo
對象和一個getType()
方法,您將執行以下操作:
Foo foo = ... // Existing Foo object
Class<V> type = foo.getType();
V value = instantiate(type); // TODO: Implement instatiate()
Bar<V> bar = new Bar(value);
然后,訣竅是instantiate()
方法的實現。 如果Class<V>
具有一個無參數的構造函數,那么您可以調用
V value = type.newInstance();
但是,並非所有類都具有默認構造函數,因此沒有針對所有情況的通用解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.