views:

87

answers:

2

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding Array type. The best I could come up with is this:

Class arrayOfFooClass = java.lang.reflect.Array.newInstance(fooClass, 0).getClass();

Is there a way to do this without creating the new instance?

+2  A: 
Class stringArrayClass = Class.forName("[Ljava.lang.String;");

You may replace java.lang.String by your object type.

Source: Jenkov Blog

Christian Strempfer
He starts with the above and ends up with what I have. So I guess the `newInstance` is the cleanest way to do this.
antrix
It actually works both ways, but you said you don't want to create a new instance.
Christian Strempfer
True. I was actually looking for a cleaner solution. It is not that I don't want the new instance but that I'd rather not have one :-)
antrix
A: 
Class stringArrayOfClass = String[].class;
Michael Wiles
I don't know the type in advance; it is in a Class variable. So your method wouldn't work.
antrix
Thanks for pointing that out
Michael Wiles