Community
Participate
Working Groups
It would be nice to have a compiler option to flag unnecessary explicit type casts.
Good suggestion. Post 2.1
Yes indeed, that would be super. The best reason for the feature is the case we have right now where we have discovered some nice interface refactoring that will clean things up greatly for us. But the most tedious part of the clean up is to go through our giant pile of code and remove the no longer needed type casts. Thank you for considering this request as soon as the 2.1 tree re-opens!
Note though that unnecessary casts are optimized out by the compiler.
reopen
One thing to keep in mind: String s = ...; Thread t = ...; Object o = bool ? s : (Object)t; The cast isn't unnecessary (optimized out, but necessary for conditional operator type resolution).
Other nasty case: class X { void foo(String s) { ... } void foo(Thread t) { ... } void bar(Object o) { if (o instance String) { foo((String)o); // necessary cast } else if (o instanceof Thread){ foo((Thread)o); // necessary cast } } }
Actually my previous case was fine, but the following is problematic: However the following is a nasty case: class X { void foo(String s) { ... } void foo(Object o) { ... } void bar() { foo((Object)"hello"); foo((String) null); } }
Previous case also affects allocation expression, anonymous type declarations and explicit constructor calls. Also numeric promotion in operators is troublesome. Finally, instanceof operator should also diagnose unnecessary case (quite trivial).
I am not flagging unnecessary narrowing cast, since removing these may change the end program behavior, however it is still useful information for end-user. foo((String) new Object()); // program would have thrown ClassCastException at runtime with cast in. void foo(Object o) {} Will not check for this (for now)
Considered narrowing scenario as well. Added optional diagnosis for unnecessary cast or instanceof operations (matching problem IDs are IProblem.UnnecessaryCast, IProblem.UnnecessaryArgumentCast, IProblem.UnnecessaryInstanceof). * COMPILER / Reporting Unnecessary Type Check * When enabled, the compiler will issue an error or a warning when a cast or an instanceof operation * is unnecessary. * - option id: "org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck" * - possible values: { "error", "warning", "ignore" } * - default: "ignore"
Note: will not complain about unnecessary narrowing casts on receiver (message or field access) since these may induce change in constant pool for target >= 1.2 (pool references contain the actual receiver type, instead of the declaring class).
Verified.