java - 如何检查一个对象是否是某种类型的数组

标签 java reflection field

我有一个对象 Field 字段

我想检查 fieldFoo 类型的对象还是数组:Foo[]

伪代码:

if field.getType() is Foo || field.getType is Foo[]

这可能吗?

我试过了

if (field.getType().isArray())
    // do something

但这只允许我检查 field 是否是一个数组。

相反,这样做只会检查它是否是 Foo 的对象

if (Foo.class.isAssignableFrom(field.getType())
     // do something

知道怎么做吗?

谢谢。

最佳答案

这是我曾经用过的一些代码,用于处理 Java 中所有基本类型的数组。由于它们不扩展 Object 类,因此对 Object[] 的 instanceof 检查是不够的。

/* Check if the given object is an array. */
if (object.getClass().isArray()) {

    Class<?> componentType;
    componentType = object.getClass().getComponentType();

    if (componentType.isPrimitive()) {

        if (boolean.class.isAssignableFrom(componentType)) {
            for (boolean anElement : (boolean[]) object) {
                /* ... */
            }
        }

        else if (byte.class.isAssignableFrom(componentType)) {
            /* ... */
        }

        else if (char.class.isAssignableFrom(componentType)) {
            /* ... */
        }

        else if (double.class.isAssignableFrom(componentType)) {
            /* ... */
        }

        else if (float.class.isAssignableFrom(componentType)) {
            /* ... */
        }

        else if (int.class.isAssignableFrom(componentType)) {
            /* ... */
        }

        else if (long.class.isAssignableFrom(componentType)) {
            /* ... */
        }

        else if (short.class.isAssignableFrom(componentType)) {
            /* ... */
        }

        /* No else. No other primitive types exist. */
    }

    else {
        /* Do something with Object[] here. */
    }
}

关于java - 如何检查一个对象是否是某种类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11107812/

相关文章:

Java 反射为 java pojo 设置值

swift - 是否有 C#'s ' nameof()' 语句的 Swift 等价物?

mysql - 我如何需要一个mysql字段?

java - 如何更新 Tomcat 中的 Java 类文件并节省正常运行时间

java.time.format.DateTimeParseException : Text '2016-2-2' could not be parsed at index 5

c# - 从 C# 类获取 JSON PropertyName,例如 json 属性的 "nameof(class.prop)"?

javascript - 如果对上一个文本进行了编辑,光标会跳到文本末尾

ruby-on-rails - collection_select类型字段上的必填字段

java - 远程执行交互式 CLI 程序

java - 仅打包依赖项中必要的类