Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4517644

Core reflection setter type conversion spec bugs

XMLWordPrintable



      Name: nt126004 Date: 10/22/2001


      java version "1.4.0-beta2"
      Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-beta2-b77)
      Java HotSpot(TM) Client VM (build 1.4.0-beta2-b77, mixed mode)


      The documentation for java.lang.reflect.Array.set(Object, int, Object) does not
      properly document what happens when an object array component type does not
      match the argument type. The documentation does cover the case of primitive
      arrays, but this is not enough information: "IllegalArgumentException - If the
      specified object argument is not an array, or if the array component type is
      primitive and the specified value cannot be converted to the primitive type by a
      combination of unwrapping and identity or widening conversions"

      In writing an independent implementation, it is not obvious whether I should
      throw ArrayStoreException or IllegalArgumentException. My guess would have been
      the former, as this requires less coding effort, but it contradicts the behavior
      of the JDK. This method should add documentation for the appropriate error.

      // Example demonstrating which exception is thrown:
      class Foo {
        public static void main(String[] args) {
          String[] s = {""};
          java.lang.reflect.Array.set(s, 0, new Integer(1));
        }
      }

      // naive implementation, which throws ArrayStoreException instead
      public static void set(Object array, int index, Object value) {
        if (array instanceof Object[])
          ((Object[]) array)[index] = value;
        else if (value instanceof Boolean)
          setBoolean(((Boolean) value).booleanValue());
        ...
        else if (value instanceof Double)
          setDouble(((Double) value).doubleValue());
        else if (array == null)
          throw new NullPointerException();
        else throw new IllegalArgumentException();
      }

      Checking for the wrong array type requires catching the ArrayStoreException, or
      else more reflective work on the class object in advace.
      public static void set(Object array, int index, Object value) {
        if (array instanceof Object[]) {
          if (array.getClass().getComponentType().isInstance(value))
            ((Object[]) array)[index] = value;
          else throw new IllegalArgumentException();
        }
        ...
      }
      (Review ID: 134139)
      ======================================================================

            liach Chen Liang
            nthompsosunw Nathanael Thompson (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Imported:
              Indexed: