简体   繁体   中英

How to instantiate a class just by having the class object and cast the result just by using the class from which it was instantiated?

I have the following problem: I have a class object(MyClass.class) and from that class object i need to instantiate an object.That is the easy part ois MyClass.class.getDeclaredConstructor().newInstance() (the class has only one constructor which takes no arguments).

The tricky part(or so i think) is to cast the resulted object to the appropriate type(MyClass) using the class object with which i created. Note that i can't write the following code (MyClass)MyClass.class.getDeclaredConstructor().newInstance()

If someone can help me with this that would be much appreciated.

Write:

MyClass.class.cast(myInstance);

See also the relevant Javadoc . Not that this would be very useful apart from null-checking and type-checking:

public T cast(Object obj) {
    if (obj != null && !isInstance(obj))
        throw new ClassCastException(cannotCastMsg(obj));
    return (T) obj;
}

... but this is how you cast a class using reflection, and I suspect that this question is about some test or assignment anyway

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