Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an object Field field.

I'd like to check if field is either an object of type Foo or an array: 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 field is an array.

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

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

Any idea how to do this?

Thanks.

like image 919
One Two Three Avatar asked Jun 19 '12 19:06

One Two Three


People also ask

How do you check if an object is an array in react?

To find an object in an array in React: Call the find() method on the array, passing it a function. The function should return an equality check on the relevant property. The find() method returns the first value in the array that satisfies the condition.

Is object an array JavaScript?

Arrays are Objects Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.


1 Answers

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[]");
            } 
        }
}

}

like image 52
User Avatar answered Sep 29 '22 01:09

User