简体   繁体   English

是否可以通过将“ new Object()”强制转换为泛型类来实例化泛型类?

[英]Is it possible to instantiate a generic class by casting a “new Object()” as the generic class?

So I am attempting to create a class which uses a generic which extends an abstract class. 因此,我尝试创建一个使用泛型的类,该类扩展了抽象类。 Ex. 例如

public abstract class Template<C extends Abstract>

However, I need to instantiate this 'C' within my class. 但是,我需要在我的课程中实例化此“ C”。 I figured I might be able to do this: 我认为我可以做到这一点:

C s = (C) ((C)new Object()).getClass().getConstructor(Known.class,AnotherKnown.class).newInstance(objectOfKnownType,objectOfAnotherKnownType);

So my question is basically whether this is possible. 所以我的问题基本上是这是否可能。 I feel like the 我感觉像

((C) new Object()).getClass()

might give me some problems. 可能会给我一些问题。

What if i changed it to: 如果我将其更改为:

C a;
C s = (C) (a.getClass().getConstructor( ... ).newInstance( ... ));
(C) new Object()

is not valid and may give you a ClassCastException later, since an Object is not a C . 是无效的,并且稍后可能会给您ClassCastException ,因为Object不是C

The way generics are implemented means Template will have no knowledge of the C it was instantiated with, you will have to create a method or constructor that takes a Class object. 泛型的实现方式意味着Template将不了解实例化的C ,您将必须创建一个采用Class对象的方法或构造函数。

public abstract class Template<C extends Abstract>
{
    private Class<C> classOfC;

    public Template( Class<C> clazz ) {
        classOfC = clazz;
    }
}

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

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