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

(reflect) Add a Class.castTo method

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • 5.0
    • core-libs
    • None

      When compiling this method:

          <E> E m(Object o, Class<E> e) {
              if (e.isInstance(o)) {
                  return (E) o;
              }
              ...
          }

      the compiler (correctly) reports "unchecked cast to type E".

      It's clear though that this code is completely type-safe. Unfortunately
      the type check is at the reflective level, the cast is at the
      language level, and there's no way to tie the two together and
      eliminate the warning.

      It's annoying to have the compiler warning about a danger that
      you know doesn't apply, and to have no way to silence it.

      The code fragment above is a toy example, but the idiom is an
      extremely important one for use with generics. The idiom would be used,
      for example, by a method that takes a set of mammals and can return --
      based on a Class object that gets passed in -- either a Set<Bear> or
      a Set<Moose>:

          <M extends Mammal> Set<M> some(Set<? extends Mammal> all,
                                          Class<M> resultType) {
              ...
              result.add((M) one);
              return result;
          }


      Request: add a method to java.lang.Class<T>:

          /**
           * Casts an object to the class or interface represented
           * by this <tt>Class</tt> object.
           *
           * @throws ClassCastException if the object is not
           * assignment-compatible with yada yada yada.
           */
          public T castTo(Object obj);

            iris Iris Clark
            sseligmasunw Scott Seligman (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: