[英]J2ME BlackBerry creating instance from array class
Is there a way to create an array from a Class
object dynamically using something like 有没有一种方法可以使用类似的方法从
Class
对象动态创建数组
MyClass[].newInstance();
I'm aware that it throws an InstantiationException
, but is there a way for me to instantiate an array indicating its type with a Class
object? 我知道它引发了
InstantiationException
,但是我有没有办法用Class
对象实例化一个指示其类型的数组?
Since java.lang.reflect.Array.newInstance() is not available in J2ME, I think you'd need a loop to do this for each object: 由于J2ME中不提供java.lang.reflect.Array.newInstance() ,因此我认为您需要一个循环才能对每个对象执行此操作:
private Object[] createArray(String fullClassName, int length) {
Object[] objects = new Object[length];
try {
Class c = Class.forName(fullClassName);
for (int i = 0; i < objects.length; i++) {
objects[i] = c.newInstance();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return objects;
}
and remember to fully-qualify the name (if you're using stringified class names): 并记住要完全限定名称(如果您使用的是字符串化的类名称):
Object[] array = createArray("mypackage.Widget", 10);
with 同
package mypackage;
public class Widget {
public int foo() {
return 5;
}
}
Note that the getConstructor() method is not available in the BlackBerry Class , so you're limited to creating objects with no-argument constructors. 请注意, BlackBerry Class中没有getConstructor()方法 ,因此您只能使用无参数构造函数创建对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.