简体   繁体   中英

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. 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 .

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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