Java:如何创建具有“ Class”对象的实例?

时间:2019-01-30 13:17:52

标签: java class generics

美好的一天,

在类a中有一个“类”类型的数据成员,该成员在构造函数中初始化。然后,我想创建此类的对象(实例)。怎么做?

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();
    }
}

1 个答案:

答案 0 :(得分:1)

您想要的是使您的testClass类通用。您可以将类型参数用作anInstance的数据类型和inputClass类类型的类型参数:

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();
    }
}

您可能想将T限制为某些类型,因此也可能希望使其受限制。