使用Class <! - ? - >变量实例化Parameterized Type类

时间:2015-06-02 20:21:22

标签: java generics parameterized-types

(注意:我在这个类似的域名中搜索了多个关于SO的问题,但我从未遇到过针对我的想法的答案。)

考虑我是否有一个类或枚举for(int x = 0; x < sparse_mat.size(1); x++) { if(sparse_mat.ref<int>(y,x) != 0) std::cout<<x<<std::endl; } ,其中每个实例都有一个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的{​​{1}}字段中的类型实例化Class<?> type的实例?例如,我会用静态方法或某种工厂方法来调用它。

编辑:

要指定Bar的功能:Bar使用简单的getter / setter包装值,并且具有一致的接口,但是类型未知。我的想法的好处是基于Foo的实例创建Bar的实例。例如,使用FooFoo.type)值来实例化Foo.A.type,而不事先知道Integer.class的值为Bar<Integer>。< / p>

1 个答案:

答案 0 :(得分:1)

鉴于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>有一个no-args构造函数,那么你可以调用

V value = type.newInstance();

但并非所有类都有默认构造函数,因此对于所有情况都没有通用解决方案。

相关问题