[英]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 : 您可以使用反射从Class
对象创建实例:
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. 当然,您可能想从方法中返回创建的实例,并且必须处理newInstance
可能引发的某些检查的异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.