1

I have an object, c, of type Class (I get hold of the object in runtime so I can't tell in compile-time which class it represents.)

Suppose c represents the class Foo. I now want to get hold of a Class-instance which represents Foo[].

How is this done best using the standard Java API?

aioobe
  • 399,198
  • 105
  • 792
  • 807
  • 1
    I think you're going to have to provide a simple example of your intention, it's not very clear from the question... – Nim Mar 28 '12 at 13:27
  • 1
    http://stackoverflow.com/questions/77387/how-to-instantiate-a-java-array-given-an-array-type-at-runtime – Dave Newton Mar 28 '12 at 13:28
  • yes the above will work - but if you need to do that - in majority of case you have a badly designed application (i.e. polymorphism usually handles everything you need the right way) – scibuff Mar 28 '12 at 13:32
  • I'm developing something similar to a compiler and the particular use case is quite complicated. – aioobe Mar 28 '12 at 13:38

3 Answers3

3

According to http://tutorials.jenkov.com/java-reflection/arrays.html, one of the ways is:

Class arrayClass = java.lang.reflect.Array.newInstance(c, 0).getClass();

This looks like a cheat, but it's definitely cleaner than playing with the class names.

Vlad
  • 34,303
  • 6
  • 78
  • 192
1

Here's an example of how to do this:

import java.lang.reflect.Array;
public class ReflectTest {
    public static void main(String[] args) {
        Foo c = new ReflectTest().new Foo();
        Foo[] foos = (Foo[]) Array.newInstance(c.getClass(), 5);
    }
    class Foo {
    }
}
Paul Sanwald
  • 10,381
  • 5
  • 41
  • 58
0

From what I can see in my test, this should work:

Class c = ...
Class cArr = java.lang.reflect.Array.newInstance(c, 1).getClass();
Aleks G
  • 54,795
  • 26
  • 160
  • 252