How to see if an object is an array without using reflection?

前端 未结 6 1808
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 04:08

How can I see in Java if an Object is an array without using reflection? And how can I iterate through all items without using reflection?

I use Google GWT so I am n

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 04:44

    There is no subtyping relationship between arrays of primitive type, or between an array of a primitive type and array of a reference type. See JLS 4.10.3.

    Therefore, the following is incorrect as a test to see if obj is an array of any kind:

    // INCORRECT!
    public boolean isArray(final Object obj) {
        return obj instanceof Object[];
    }
    

    Specifically, it doesn't work if obj is 1-D array of primitives. (It does work for primitive arrays with higher dimensions though, because all array types are subtypes of Object. But it is moot in this case.)

    I use Google GWT so I am not allowed to use reflection :(

    The best solution (to the isArray array part of the question) depends on what counts as "using reflection".

    • In GWT, calling obj.getClass().isArray() does not count as using reflection1, so that is the best solution.

    • Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof expressions.

      public boolean isArray(final Object obj) {
          return obj instanceof Object[] || obj instanceof boolean[] ||
             obj instanceof byte[] || obj instanceof short[] ||
             obj instanceof char[] || obj instanceof int[] ||
             obj instanceof long[] || obj instanceof float[] ||
             obj instanceof double[];
      }
      
    • You could also try messing around with the name of the object's class as follows, but the call to obj.getClass() is bordering on reflection.

      public boolean isArray(final Object obj) {
          return obj.getClass().toString().charAt(0) == '[';
      }
      

    1 - More precisely, the Class.isArray method is listed as supported by GWT in this page.

提交回复
热议问题