简体   繁体   中英

J2ME BlackBerry creating instance from array class

Is there a way to create an array from a Class object dynamically using something like

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?

Since java.lang.reflect.Array.newInstance() is not available in J2ME, I think you'd need a loop to do this for each object:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM