简体   繁体   English

抓住Foo []。给出Foo.class类

[英]Get hold of Foo[].class given Foo.class

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.) 我有一个类型Class c的对象(我在运行时得到了对象,所以我无法在编译时告诉它代表哪个类。)

Suppose c represents the class Foo . 假设c代表Foo类。 I now want to get hold of a Class -instance which represents Foo[] . 我现在想要获得一个代表Foo[]Class -instance。

How is this done best using the standard Java API? 使用标准Java API如何做到最好?

According to http://tutorials.jenkov.com/java-reflection/arrays.html , one of the ways is: 根据http://tutorials.jenkov.com/java-reflection/arrays.html ,其中一种方法是:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM