考虑我是否有一个类或枚举 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;
}
}
是否可以实例化 Bar
的实例类型来自 Class<?> type
给定的字段Foo
不知道 Foo.type
的具体类型?例如,我会在静态方法或某种工厂方法中调用它。
编辑:
指定Bar的功能:Bar用简单的getter/setter包装一个值,并且具有一致的接口(interface),但类型未知。我的想法的好处是基于 Foo 的实例创建 Bar 的实例。例如,使用值Foo.A.type
(即 Integer.class
)实例化 Bar<Integer>
事先不知道Foo.A.type
值为 Integer.class
.
最佳答案
给定 Bar
中的构造函数类,以便实例化一个新的 Bar<V>
对象,您需要一个 V
类型的对象.
所以,你的问题转化为实例化 Class<V>
类型的对象。更具体地说,假设现有 Foo
对象和一个getType()
Foo
中的方法类,你会做类似的事情:
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();
不过,并非所有类都有默认构造函数,因此没有适用于所有情况的通用解决方案。
关于java - 使用 Class<?> 变量实例化参数化类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30605846/