美好的一天,
在类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();
}
}
答案 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
限制为某些类型,因此也可能希望使其受限制。