【问题标题】:How to get source class of static[] array如何获取静态[]数组的源类
【发布时间】:2020-01-17 09:15:07
【问题描述】:

我想要静态数组中的底层类。例如,如果它说String[].class 我想得到String.class

    String[] foo = new String[0];
    System.out.println(foo.getClass());

输出

class [Ljava.lang.String;

【问题讨论】:

    标签: java arrays static


    【解决方案1】:

    使用Class#getComponentType():

    Class<?> type = foo.getClass().getComponentType();
    System.out.println(type); // class java.lang.String
    

    来自docs

    返回表示数组组件类型的类。如果此类不代表数组类,则此方法返回 null。

    【讨论】:

    • 如果您不确定foo 是一个数组,您可能需要先检查foo.getClass().isArray(),而不是测试getComponentType() 是否返回null。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2015-11-07
    • 1970-01-01
    相关资源
    最近更新 更多