Android 动态类创建给出 java.lang.InstantiationException
当我尝试创建 Android UI 组件的动态实例时,它给了我“java.lang.InstantiationException”。
示例代码:
Class components[] = {TextView.class, Button.class,...}
Component mControl = null;
...
...
mControl = (Component) components[nIndexOfControl].newInstance();
有人可以指导我,实现上述目标的最佳方法是什么,因为我想为每个小部件保存 if..else ?
When I am trying to create a dynamic instance of Android UI Component, it gives me "java.lang.InstantiationException".
Sample Code:
Class components[] = {TextView.class, Button.class,...}
Component mControl = null;
...
...
mControl = (Component) components[nIndexOfControl].newInstance();
Can some one guide me, what is the best way to achieve the above as I want to save if..else for each widget?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
TextView
类没有默认构造函数。三个可用的构造函数是:Button
类相同:您需要至少传递
Context
变量来实例化所有 UI(View
的后代)控件。接下来更改您的代码:
The
TextView
class does not have default constructor. Three availabale constructors are:Same thing for
Button
class:You need to pass at least
Context
variable to instantiate all UI (descendants ofView
) controls.Change your code next way:
View 对象没有默认构造函数< /a>.查看 Class.newInstance()。如果找不到匹配的构造函数,它会抛出
InstantiationException
。There is not default constructor for View objects. Take a look at the javadoc for Class.newInstance(). It throws an
InstantiationException
if no matching constructor is found.我在 Google 中搜索了“java class.newInstance”,并且:
a)我找到了 java.lang.Class 类的文档,其中解释了抛出此异常的确切情况:
b)建议的搜索词是“java class” .newinstance withparameters”,其中找到了处理“类没有空构造函数”情况的几种方法,包括来自 StackOverflow 的一些结果。
您的类列表中没有数组类、基本类型或“void”,并且“其他原因”不太可能(并且无论如何都会在异常消息中进行解释)。如果该类是抽象类或接口,那么您根本无法以任何方式实例化它。
I searched with Google for 'java class.newInstance' and:
a) I found the documentation for the java.lang.Class class, which explains the exact circumstances under which this exception is thrown:
b) A suggested search term was "java class.newinstance with parameters", which finds several approaches for dealing with the "class has no nullary constructor" case, including some results from StackOverflow.
You don't have array classes, primitive types or 'void' in your list of classes, and "some other reason" is unlikely (and would be explained in the exception message anyway). If the class is abstract or an interface, then you simply can't instantiate it in any way.