JDK-6542176 : New static castType method as an alternative for @SuppressWarnings("unchecked")
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2007-04-03
  • Updated: 2010-04-04
  • Resolved: 2007-04-03
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE REQUEST :
Sometimes we must mix generics and non-generics code. The simplest example: we have two objects o1 and o2, declared as "Object", and need to compare them via Comparable: ((Comparable)o1).compare(o2). The most "popular" and annoying compiler warning here is "unchecked cast", when we need to cast some raw type to a generics one.

Of course, we may use @SuppressWarnings("unchecked") annotation any time when we really need such casting. But it does not beautify the code. Moreover, some old IDEs do not "understand" it, because there was no this annotation in the first releases of Java 1.5.

Could you add the following static method into System or Class:

    @SuppressWarnings("unchecked")
    public static <T> T castType(Object object) {
        return (T)object;
    }

It allows to avoid "unchecked cast" warning or using @SuppressWarnings in most cases while compiling the user's code.


JUSTIFICATION :
Often using @SuppressWarnings("unchecked") chokes the Java code and does not help in old IDEs (though these IDEs allow compilation with JDK 1.7).



CUSTOMER SUBMITTED WORKAROUND :
I've implemented such a method in my package-private library and call this always instead unsafe type casing.

Comments
WORK AROUND For some cases you might find the Class.cast method a useful alternative.
03-04-2007

EVALUATION Such a method would not be type safe and would go against the purpose of emitting warnings in the first place. I have closed this as a duplicate of 5098163 as that would give us the ability to implement the casts and thus not emit a warning all together.
03-04-2007