实例化内部类
我有一个实用方法,当从中删除不相关的逻辑时,简化的方法将如下所示:
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
,那么即使 Bar
是公共的,newInstance()
方法也将不起作用,因为它会抛出 java.lang.InstantiationException
代码>.
有没有办法动态实例化内部类?
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;
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果它确实是一个内部类而不是嵌套(静态)类,则有一个隐式构造函数参数,它是对外部类实例的引用。 在此阶段您不能使用 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:更通用的东西:
Something more generic:
仅当 clazz 表示抽象类或接口时才会抛出此异常。 您确定要传递代表具体类的 Class 对象吗?
This exception will be thrown only if clazz represents either an abstract class or an interface. Are you sure you're passing a Class object that represents a concrete class?
在 Jmockit 1.41 中,使用:
ConstructorReflection.newInstance
In Jmockit 1.41, use this:
ConstructorReflection.newInstance