JDK-4957200 : (reflect) Add a Class.castTo method
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: solaris_9
  • CPU: sparc
  • Submitted: 2003-11-20
  • Updated: 2012-09-28
  • Resolved: 2003-11-20
Related Reports
Duplicate :  
Description
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);

Comments
EVALUATION Duplicate 4881275. -- iag@sfbay 2003-11-20
20-11-2003