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

please add a typesafe cast for Class<?> types

XMLWordPrintable

      There are one or two places where method parameters of type Class will now
      be more specific, for example

           public DragGestureRecognizer createDragGestureRecognizer(
              Class<? extends MyDragGestureRecognizer> abstractRecognizerClass, ...

      And Class.forName() now returns Class<?>.

      In -source 1.5, this can break a client that uses

          dgr.createDragGestureRecognizer(Class.forName("MyDragGestureRecognizer"));

      and yet the programmer has no way to generify the client soundly. How
      should clients adjust their code? Adding a cast (in this case to
      Class<? extends DragGestureRecognizer>) provokes an unchecked warning,
      and there is no way to get rid of it. Given that some API designers
      will want to create factory-like typesafe APIs in which clients will use
      Class.forName(), there needs to be a way for clients to use the API
      safely. I suggest adding the following method to class Class:

        class Class<T> { ...

          public <U> Class<? extends U> asSubclass(Class<U> clazz) {
            if (clazz.isAssignableFrom(this))
              return (Class<? extends U>) this;
            else
              throw new ClassCastException(this);
          }
        }

            gafter Neal Gafter (Inactive)
            gafter Neal Gafter (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: