2

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?

Nate
  • 31,017
  • 13
  • 83
  • 207
danielrvt-sgb
  • 1,118
  • 5
  • 17
  • 33
  • 1
    Could you clarify? Sounds like you want an array where the type can be set/changed. Which I don't think is possible. Closest I can think of is `Object [] array = new MyClass[10];` You could maybe use that idea and make a class that copies/casts objects in an array to another type. – Kevin Jun 28 '13 at 07:41
  • related?: http://stackoverflow.com/q/1632130/813951 – Mister Smith Jun 28 '13 at 13:01
  • 1
    For the first comment: I don't know the class, (i's a variable of the type class). For the second comment: I'm using J2ME. Bottom line, is not posible. – danielrvt-sgb Jun 28 '13 at 22:25

1 Answers1

0

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.

Community
  • 1
  • 1
Nate
  • 31,017
  • 13
  • 83
  • 207
  • Using the stringified name of the class is the solution here. But only if I'm using a concrete class, if the array is abstract or an interface, there is no way to get the array component typeto instantiate those. – danielrvt-sgb Jul 01 '13 at 15:22
  • @danielrvt-sgb, you don't have to use string names if you don't want to. In my example, you can change `createArray()` to take `Class c` as a parameter. But, **somewhere**, you will need to decide to create a **concrete** class. You cannot instantiate abstract classes, or interfaces. Something will have to decide which subclass of an abstract class, or which implementation of an interface will be created. – Nate Jul 01 '13 at 21:25
  • Also, please remember to vote for answers that are useful. Questions like these don't get much attention, and voting is the way to identify answers that work. Thanks. – Nate Jul 01 '13 at 21:26