Proposed Rule Name: UnnecessaryBoxing (pmd7)
The rule "PrimitiveWrapperInstantiation" has been implemented for PMD 6.37.0.
Proposed Category: Best Practices
Description:
The new rules that merges together:
(all in category performance)
The first rule flags valueOf
calls, and only cares about primitive wrappers that are created and unboxed explicitly in the same expression, like Integer.valueOf(0).intValue()
. This is contrived and no one does it: the rule has zero violations in checkstyle, spring, or the jdk.
The other rules flag uses of the constructors of primitive wrappers (but for some reason not Double
, Character
or Float
). The rationale is that using valueOf
may avoid creating a new instance. This is true, but also,
valueOf
can be replaced nearly everywhere by autoboxingSo the idea is to merge all those into a new UnnecessaryBoxing
rule that cares about:
Object i = Integer.valueOf(2)
int i = integer.intValue()
Object i = integer.intValue()
(would rebox the int)int i = Integer.valueOf(0)
(would unbox the integer)Integer.valueOf(integer)
(unboxes integer, then boxes it)Integer.valueOf(someString)
where an int is expected: Integer.parseInt
is more appropriate. -> [java] UnnecessaryBoxing - check for Integer.valueOf(String) calls #3500if ((boolean) Boolean.TRUE) ...
) are unnecessary -> this is left to rule UnnecessaryCast, see [java] Generalize UnnecessaryCast to flag all unnecessary casts #3218The new rule PrimitiveWrapperConstructor
cares about:
new Integer(1)
. Instead, Integer.valueOf(1)
should be used.This applies to all primitives.
Code Sample: This should include code, that should be flagged by the rule. If possible, the "correct" code
according to this new rule should also be demonstrated.
class Scratch { public static void main(String[] args) { Integer anInteger = 2; // ok Object a = Integer.valueOf(2); // explicit boxing where the value would be autoboxed int b = anInteger.intValue(); // explicit unboxing where the value would be auto-unboxed Object c = anInteger.intValue(); // unboxing where the value is immediately reboxed int i = Integer.valueOf(0); // boxing where the value is immediately unboxed Integer.valueOf(anInteger); // boxing of already boxed value if ((boolean) Boolean.TRUE); // Casts that unboxes the operand // Actually a cast to a wrapper can be treated just like a valueOf call // (when the cast operand is primitive) and be handled exactly like a valueOf call, // so be handled in all the situations above. Integer o = (Integer) a; // a is an Object so the cast is not redundant } }
Possible Properties:
None that I can think of.
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