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
  • 413,195
  • 112
  • 811
  • 826
  • 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
  • 35,022
  • 6
  • 77
  • 199
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,899
  • 6
  • 44
  • 59
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
  • 56,435
  • 29
  • 168
  • 265