基于参数的新类实例 [英] New instance of class based on argument
问题描述
我正在尝试创建一个函数,它接受扩展 Foo
的许多类中的一个,并在其Class中返回该对象的新实例,而不是新实例 Foo
。
I'm trying to make a function that takes one of many classes that extends Foo
, and return a new instance of that object in its Class, not a new instance of Foo
.
我确定这是一个常见问题。那里有什么好的例子吗?
I'm sure this is a common issue. Is there any good examples out there?
我从未使用过类作为输入参数,只使用类的成员。基于我搜索过的内容,应该可以这样做吗?
I have never used a class as an input parameter, only members of a class. Based on what I have searched for, this should be possible to do?
推荐答案
你传递的是类
对象作为参数,或者在 Foo
的子类的实例中?
Are you passing a Class
object as the parameter, or in instance of a subclass of Foo
?
在任何一种情况下解决方案几乎相同,你使用 newInstance 方法。
The solution is almost the same in either case, you use the newInstance method on the Class object.
/**
* Return a new subclass of the Foo class.
*/
public Foo fooFactory(Class<? extends Foo> c)
{
Foo instance = null;
try {
instance = c.newInstance();
}
catch (InstantiationException e) {
// ...
}
catch (IllegalAccessException e) {
// ...
}
return instance; // which might be null if exception occurred,
// or you might want to throw your own exception
}
如果你需要构造函数args,你可以使用Class getConstructor 方法,从那里构造函数 newInstance(...)方法。
If you need constructor args you can use the Class getConstructor method and from there the Constructor newInstance(...) method.
这篇关于基于参数的新类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!