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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11107812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:50:21  来源:igfitidea点击:

How to check if an object is an array of a certain type

javareflectionfield

提问by One Two Three

I have an object Field field.

我有一个对象Field field

I'd like to check if fieldis either an object of type Fooor an array: Foo[].

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

Psuedo code:

伪代码:

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

Is this possible?

这可能吗?

I've tried

我试过了

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

But this would only allow me to check if fieldis an array.

但这只会让我检查是否field是一个数组。

Doing this, on the contrary, will only check if it's an object of Foo

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

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

Any idea how to do this?

知道如何做到这一点吗?

Thanks.

谢谢。

回答by Claas Wilke

Here is some code I used once to handle arrays of all primitive types in Java. As they do not extend the Object class, an instanceof check for Object[] is insufficent.

这是我曾经用来处理 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. */
    }
}

回答by dnc253

Assuming the Field you mention is a java.lang.reflect.Field, you can just do

假设你提到的 Field 是 a java.lang.reflect.Field,你可以做

field.getType().equals(Foo.class) || field.getType().equals(Foo[].class)

回答by Ixx

Simple compare should work

简单的比较应该有效

import java.lang.reflect.Field;

public class Main {

String[] myStringArray;
String[] myStringArray2;

Object[] myObjectArray;

String str;


public static void main(String... args) {
        Field[] flds = Main.class.getDeclaredFields();
        for (Field f : flds) {
            Class<?> c = f.getType();

            if (c == String[].class) {
                System.out.println("field" + f.getName() + " is String[]");
            } 
            if (c == String.class) {
                System.out.println("field" + f.getName() + " is String");
            }
            if (c == Object[].class) {
                System.out.println("field" + f.getName() + " is Object[]");
            } 
        }
}

}

}

回答by smcg

if (field instanceof Object[])

That should do it.

那应该这样做。

回答by Mark Peters

Since array types are reified, you can just use

由于数组类型被具体化,您可以只使用

if ( field.getType() == Foo.class || field.getType() == Foo[].class ) {
}

Full example:

完整示例:

public class Scratchpad {
    String[] strings;

    public static void main(String[] args) throws NoSuchFieldException {
        if (Scratchpad.class.getDeclaredField("strings").getType() == String[].class) {
            System.out.println("They're Strings!");
        }

        if (Scratchpad.class.getDeclaredField("strings").getType() == Long[].class) {
            System.out.println("They're Longs!");
        }
    }
}

回答by Kennet

I would do something like this:

我会做这样的事情:

public static void main(String[] args) {
    Foo foo = new Foo();
    Foo[] other = new Foo[1];
    other[0] = new Foo();

    System.out.println(isFooOrArrayOfFoo(foo));
    System.out.println(isFooOrArrayOfFoo(other[0]));
    System.out.println(isFooOrArrayOfFoo(new Object()));
}

private static boolean isFooOrArrayOfFoo(Object o) {
    return (o instanceof Foo || o.getClass().equals(Foo.class) && o.getClass().isArray());
}