In Java, how do I dynamically determine the type of an array?

后端 未结 3 1376
醉梦人生
醉梦人生 2020-12-06 04:26
Object o = new Long[0]
System.out.println( o.getClass().isArray() )
System.out.println( o.getClass().getName() )
Class ofArray = ???

Running the fi

3条回答
  •  爱一瞬间的悲伤
    2020-12-06 04:35

    @ddimitrov is the correct answer. Put into code it looks like this:

    public  Class testArray(T[] array) {
        return array.getClass().getComponentType();
    }
    

    Even more generally, we can test first to see if the type represents an array, and then get its component:

    Object maybeArray = ...
    Class clazz = maybeArray.getClass();
    if (clazz.isArray()) {
        System.out.printf("Array of type %s", clazz.getComponentType());
    } else {
        System.out.println("Not an array");
    }
    

    A specific example would be applying this method to an array for which the component type is already known:

    String[] arr = {"Daniel", "Chris", "Joseph"};
    arr.getClass().getComponentType();              // => java.lang.String
    

    Pretty straightforward!

提交回复
热议问题