在java中,我可以使用类对象来动态实例化该类型的类吗?从类对象实例化类
即我想要这样的功能。
Object foo(Class type) {
// return new object of type 'type'
}
在java中,我可以使用类对象来动态实例化该类型的类吗?从类对象实例化类
即我想要这样的功能。
Object foo(Class type) {
// return new object of type 'type'
}
您可以使用Class.newInstance
:
Object foo(Class type)
throws InstantiationException, IllegalAccessException {
return type.newInstance();
}
...但是,假设有一个无参数的构造函数。一个更强大的路线是通过Class.getConstructor
或Class.getConstructors
,它会带您使用java.lang.reflect
包中的Reflection物件。
用途:
type.newInstance()
对于使用空costructor,或者使用方法type.getConstructor(..)来获取相关的构造函数,然后调用它创建一个实例。
是的,它被称为反射。您可以使用类newInstance()
方法。
使用newInstance()方法。
你可以阅读更多关于它在: http://java.sun.com/docs/books/tutorial/reflect/index.html 此文章有很好的信息:http://stackoverflow.com /问题/ 37628 /什么 - 是 - 反射和为什么 - 是 - 它无用 – RonK 2010-06-14 11:27:24