简体   繁体   中英

Java: how create instance having the "Class" object?

Good day,

within a class a have a "Class" type data member which I initialize in constructor. Then I would like to create objects (instances) of this class. How to do it?

import java.lang.reflect.InvocationTargetException;

public class runMe {
    public static void main(String[] args) throws NoSuchMethodException,
            InstantiationException, IllegalAccessException, InvocationTargetException {
        String testStr = "XXX";
        testClass cls = new testClass(testStr.getClass());
        cls.createInstance();
    }
}

import java.lang.reflect.InvocationTargetException;

public class testClass {
    Class<?> myClass;

    testClass(Class inputClass) {
        this.myClass = inputClass;
    }

    void createInstance() throws NoSuchMethodException,
            InstantiationException, IllegalAccessException, InvocationTargetException {
        myClass.getDeclaredConstructor().newInstance(); // this works
       //QUESTION, how to do something like this (and return, in this example a String):
       myClass anInstance = myClass.getDeclaredConstructor().newInstance();
    }
}

What you want is to make your testClass class generic. You can use a type parameter as the data type of anInstance and as the type argument for your inputClass class type:

class testClass<T> {
    Class<T> myClass;

    testClass(Class<T> inputClass) {
        this.myClass = inputClass;
    }

    void createInstance() throws NoSuchMethodException, InstantiationException, 
                IllegalAccessException, InvocationTargetException {
        T anInstance = myClass.getDeclaredConstructor().newInstance();
    }
}

It's likely that you want to restrict T to certain types, so you probably want to make it bounded too.

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