0

当我尝试创建 Android UI 组件的动态实例时,它给了我“java.lang.InstantiationException”。

示例代码:

Class components[] = {TextView.class, Button.class,...}
Component mControl = null;
...
...
mControl = (Component) components[nIndexOfControl].newInstance();

有人可以指导我,实现上述目标的最佳方法是什么,因为我想为每个小部件保存 if..else?

4

3 回答 3

2

该类TextView没有默认构造函数。三个可用的构造函数是:

TextView(Context context)
TextView(Context context, AttributeSet attrs)
TextView(Context context, AttributeSet attrs, int defStyle)

上课也是一样Button

public Button (Context context)
public Button (Context context, AttributeSet attrs)
public Button (Context context, AttributeSet attrs, int defStyle) 

您至少需要传递Context变量来实例化所有 UI(的后代View)控件。


接下来更改您的代码:

Context ctx = ...;
Class<?> components[] = {TextView.class, Button.class };
Constructor<?> ctor = components[nIndexOfControl].getConstructor(Context.class);
Object obj = ctor.newInstance(ctx);
于 2011-06-28T18:36:40.837 回答
0

View objects没有默认构造函数。查看Class.newInstance()的 javadoc 。InstantiationException如果没有找到匹配的构造函数,它会抛出一个。

于 2011-06-28T18:37:23.193 回答
0

我用 Google 搜索了“java class.newInstance”并且:

a) 我找到了 java.lang.Class 类的文档,它解释了引发此异常的确切情况:

InstantiationException - if this Class represents an abstract class, an
interface, an array class, a primitive type, or void; or if the class has
no nullary constructor; or if the instantiation fails for some other reason.

b) 建议的搜索词是“java class.newinstance with parameters”,它找到了几种处理“类没有空构造函数”情况的方法,包括来自 StackOverflow 的一些结果。

您的类列表中没有数组类、原始类型或“void”,并且“其他原因”不太可能(无论如何都会在异常消息中解释)。如果该类是抽象类或接口,那么您根本无法以任何方式实例化它。

于 2011-06-28T18:40:21.780 回答