简体   繁体   中英

How do I pass a class to a function and instantiate an object of that class in the function?

Something like this. The way the class is passed is probably correct but the object instantiation method does not work. Should I approach this differently?

private void init() {
    makeObject(ClassA.class);
    makeObject(ClassB.class);
    makeObject(ClassC.class);
}

private void makeObject(Class<?> myClass) {
    new myClass();
}

You use reflection to create an instance from a Class object :

private void makeObject(Class<?> myClass) {
    Object o = myClass.newInstace();
}

Of course you probably want to return the created instance from your method, and you have to handle some checked exceptions that newInstance may throw.

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