javablackberryjava-mejava-micro-editon-sdk3.0

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?


Solution

  • 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.