简体   繁体   English

使用java.lang.Class的实例创建参数化类的实例

[英]Creating an instance of a parameterized class using an instance of java.lang.Class

Lets say that I have a parameterized class 可以说我有一个参数化的类

public class<K> MyClass {
    private K val;

    public K getVal() { return val; }

    public void setVal(K val) { this.val = val; }
}

My objective is to be able to create an instance of this class using a parameter that I pass as an argument. 我的目标是能够使用我作为参数传递的参数创建此类的实例。 This parameter is of type java.lang.Class. 此参数的类型为java.lang.Class。 Something along the lines of 遵循以下原则

public void createInstance(Class<?> klass) {
    MyClass<klass> k = new MyKlass<>();
}

Now, I know that this is incorrect. 现在,我知道这是不正确的。 I cannot pass the variable klass as a parameter to MyClass. 我无法将变量klass作为参数传递给MyClass。 But is it possible create an instance of MyClass that is parameterized with the Class represented by the klass variable? 但是是否可以创建由klass变量表示的Class参数化的MyClass实例?

is it possible create an instance of MyClass that is parameterized with the Class represented by the klass variable? 是否可以创建MyClass的实例,该实例使用klass变量表示的Class进行参数化?

No. 没有。

The reason is, as far as your program is concerned when it runs, there is no difference between a Foo<Bar> and a Foo<Baz> . 原因是,就程序运行时而言, Foo<Bar>Foo<Baz>之间没有区别。

Create it raw and cast it. 原始创建并将其转换。 Any other solution will be equivalent to that. 任何其他解决方案都将与之等效。

Expounding on Louis Wasserman's answer: 阐述路易斯·瓦瑟曼的答案:

You could create a meta-factory to spit out instances of class factories: 您可以创建一个元工厂来吐出类工厂的实例:

public class MyClassFactory<K> {
    final Class<K> klass;

    protected MyClassFactory(final Class<K> clazz) {
        klass = clazz;
    }

    protected K create() throws InstantiationException, IllegalAccessException {
        return klass.newInstance();
    }

    public static <K> MyClassFactory<K> createFactory(final Class<K> clazz) throws InstantiationException, IllegalAccessException {
        return new MyClassFactory(clazz);
    }
}

And then call it something like this: 然后将其命名为:

MyClassFactory<? extends MyClass> myClassFactory = MyClassFactory.createFactory((new MyClass<Foo>()).getClass());
MyClass<Foo> myFooClass = myClassFactory.create();
Foo foo = new Foo();
myFooClass.setVal(foo);

But you'll notice that the factories produced give you <? extends MyClass> 但是您会注意到生产的工厂给您<? extends MyClass> <? extends MyClass> , not a MyClass<Foo> , so you can also do this (with the same factory): <? extends MyClass> ,而不是MyClass<Foo> ,因此您也可以这样做(使用相同的工厂):

MyClass<Baz> myBazClass = myClassFactory.create();
Baz baz = new Baz();
myBazClass.setVal(baz);
System.out.println(myBazClass.getVal());

And unfortunately also this: 不幸的是:

 MyClass fubar = myClassFactory.create();
 Object obj = new SomeArbitraryObject();
 fubar.setVal(obj);
 System.out.println(fubar.getVal());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM