实例化内部类 [英] Instantiating an inner class
问题描述
我有一个实用工具方法,当从中删除不相关的逻辑时,简化的方法如下所示:
I have a utility method and when irrelevant logic is removed from it, the simplified method would look like this:
public static <A extends Foo> List<A> getFooList(Class<A> clazz) {
List<A> returnValue = new ArrayList<A>();
for(int i=0; i < 5; i++) {
A object = clazz.newInstance();
returnValue.add(object);
}
return returnValue;
}
问题是,如果 clazz
是一个内部类,如 Foo.Bar.class
,那么 newInstance()
方法不会即使 Bar
是公开的,因为它会抛出 java.lang.InstantiationException
。
The problem is, that if clazz
is an inner class such as Foo.Bar.class
, then the newInstance()
method will not work even if Bar
would be public, as it will throw a java.lang.InstantiationException
.
有没有办法动态实例化内部类?
Is there a way to dynamically instantiate inner classes?
推荐答案
如果真的是 inner 类而不是嵌套(静态)类,有一个隐式构造函数参数,它是对外部类实例的引用。你不能在那个阶段使用 Class.newInstance
- 你必须得到适当的构造函数。这是一个例子:
If it's genuinely an inner class instead of a nested (static) class, there's an implicit constructor parameter, which is the reference to the instance of the outer class. You can't use Class.newInstance
at that stage - you have to get the appropriate constructor. Here's an example:
import java.lang.reflect.*;
class Test
{
public static void main(String[] args) throws Exception
{
Class<Outer.Inner> clazz = Outer.Inner.class;
Constructor<Outer.Inner> ctor = clazz.getConstructor(Outer.class);
Outer outer = new Outer();
Outer.Inner instance = ctor.newInstance(outer);
}
}
class Outer
{
class Inner
{
// getConstructor only returns a public constructor. If you need
// non-public ones, use getDeclaredConstructors
public Inner() {}
}
}
这篇关于实例化内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!