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?
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 .
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 {
}
}
From what I can see in my test, this should work:
Class c = ...
Class cArr = java.lang.reflect.Array.newInstance(c, 1).getClass();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.