A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/pmd/pmd/issues/3218 below:

[java] Generalize UnnecessaryCast to flag all unnecessary casts · Issue #3218 · pmd/pmd · GitHub

Is your feature request related to a problem? Please describe. UnnecessaryCast is artificially limited to casts on collection classes. These are quite rare post java 5. The rule has zero violations in the projects on which we regression test.

Describe the solution you'd like Make the rule report any cast that is unnecessary, finally making its behavior match its name.

This is what's implemented by #3204. The implementation strategy is the following. Given a cast that looks like this:

ContextType t = (CastType) expression;

, the cast is unnecessary if the type of expression is compatible (subtype, or subtype after boxing/unboxing/widening/unchecked conversions) with both CastType and ContextType. This ensures that the cast is not narrowing, and if removed, the code will still compile. The rule is not limited to assignment contexts like in the above example.

Examples:

import java.util.function.Function;
class SomeClass {
   static {
      Object o; long l; int i;

      o = (Object) new SomeClass(); // FN
      o = (Comparable<String>) "string"; // FN

      // primitive widening
      l = (long) 2;   // FN
      l = (Long) 2;   // FN
      l = (long) 2.0; // TN (narrowing cast)
      l = (byte) i;   // TN (narrowing cast)

      // boxing/unboxing casts (since java 5)

      o = (Integer) 3; // FN (autoboxing)
      o = (Long) 3;    // TN

      // casts that give a target type to a lambda/ method ref are necessary
      o = (Function<Integer, String>) Integer::toString; // TN
   }
}

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4