-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
errorprone.xml
3502 lines (3274 loc) · 121 KB
/
errorprone.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0"?>
<ruleset name="Error Prone"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>
Rules to detect constructs that are either broken, extremely confusing or prone to runtime errors.
</description>
<rule name="AssignmentInOperand"
language="java"
since="1.03"
message="Avoid assignments in operands"
class="net.sourceforge.pmd.lang.java.rule.errorprone.AssignmentInOperandRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#assignmentinoperand">
<description>
Avoid assignments in operands; this can make code more complicated and harder to read.
</description>
<priority>3</priority>
<example>
<![CDATA[
public void bar() {
int x = 2;
if ((x = getX()) == 3) {
System.out.println("3!");
}
}
]]>
</example>
</rule>
<rule name="AssignmentToNonFinalStatic"
language="java"
since="2.2"
message="Possible unsafe assignment to non-final static field ''{0}'' in a constructor."
class="net.sourceforge.pmd.lang.java.rule.errorprone.AssignmentToNonFinalStaticRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#assignmenttononfinalstatic">
<description>
Identifies a possible unsafe usage of a static field.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class StaticField {
static int x;
public FinalFields(int y) {
x = y; // unsafe
}
}
]]>
</example>
</rule>
<rule name="AvoidAccessibilityAlteration"
language="java"
since="4.1"
message="You should not modify visibility of constructors, methods or fields using setAccessible()"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidaccessibilityalteration">
<description>
Methods such as `getDeclaredConstructors()`, `getDeclaredMethods()`, and `getDeclaredFields()` also
return private constructors, methods and fields. These can be made accessible by calling `setAccessible(true)`.
This gives access to normally protected data which violates the principle of encapsulation.
This rule detects calls to `setAccessible` and finds possible accessibility alterations.
If the call to `setAccessible` is wrapped within a `PrivilegedAction`, then the access alteration
is assumed to be deliberate and is not reported.
Note that with Java 17 the Security Manager, which is used for `PrivilegedAction` execution,
is deprecated: [JEP 411: Deprecate the Security Manager for Removal](https://openjdk.java.net/jeps/411).
For future-proof code, deliberate access alteration should be suppressed using the usual
suppression methods (e.g. by using `@SuppressWarnings` annotation).
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[
pmd-java:matchesSig("java.lang.reflect.AccessibleObject#setAccessible(boolean)")
or pmd-java:matchesSig("_#setAccessible(java.lang.reflect.AccessibleObject[],boolean)")
]
[not(ArgumentList/BooleanLiteral[@True = false()])]
(: exclude anonymous privileged action classes :)
[not(ancestor::ConstructorCall[1][pmd-java:typeIs('java.security.PrivilegedAction')]/AnonymousClassDeclaration)]
(: exclude inner privileged action classes :)
[not(ancestor::ClassOrInterfaceDeclaration[1][pmd-java:typeIs('java.security.PrivilegedAction')])]
(: exclude privileged action lambdas :)
[not(ancestor::LambdaExpression[pmd-java:typeIs('java.security.PrivilegedAction')])]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
public class Violation {
private void invalidSetAccessCalls() throws NoSuchMethodException, SecurityException {
Constructor<?> constructor = this.getClass().getDeclaredConstructor(String.class);
// call to forbidden setAccessible
constructor.setAccessible(true);
Method privateMethod = this.getClass().getDeclaredMethod("aPrivateMethod");
// call to forbidden setAccessible
privateMethod.setAccessible(true);
// deliberate accessibility alteration
String privateField = AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
try {
Field field = Violation.class.getDeclaredField("aPrivateField");
field.setAccessible(true);
return (String) field.get(null);
} catch (ReflectiveOperationException | SecurityException e) {
throw new RuntimeException(e);
}
}
});
}
}
]]>
</example>
</rule>
<rule name="AvoidAssertAsIdentifier"
language="java"
maximumLanguageVersion="1.3"
since="3.4"
message="Avoid using assert as an identifier; it became a reserved word in JDK 1.4"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidassertasidentifier">
<description>
Use of the term `assert` will conflict with newer versions of Java since it is a reserved word.
Since Java 1.4, the token `assert` became a reserved word and using it as an identifier will
result in a compilation failure for Java 1.4 and later. This rule is therefore only useful
for old Java code before Java 1.4. It can be used to identify problematic code prior to a Java update.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>//VariableDeclaratorId[@Name='assert']</value>
</property>
</properties>
<example>
<![CDATA[
public class A {
public class Foo {
String assert = "foo";
}
}
]]>
</example>
</rule>
<rule name="AvoidBranchingStatementAsLastInLoop"
language="java"
since="5.0"
class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidBranchingStatementAsLastInLoopRule"
message="Avoid using a branching statement as the last in a loop."
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidbranchingstatementaslastinloop">
<description>
Using a branching statement as the last part of a loop may be a bug, and/or is confusing.
Ensure that the usage is not a bug, or consider using another approach.
</description>
<priority>2</priority>
<example>
<![CDATA[
// unusual use of branching statement in a loop
for (int i = 0; i < 10; i++) {
if (i*i <= 25) {
continue;
}
break;
}
// this makes more sense...
for (int i = 0; i < 10; i++) {
if (i*i > 25) {
break;
}
}
]]>
</example>
</rule>
<rule name="AvoidCallingFinalize"
language="java"
since="3.0"
message="Avoid calling finalize() explicitly"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidcallingfinalize">
<description>
The method Object.finalize() is called by the garbage collector on an object when garbage collection determines
that there are no more references to the object. It should not be invoked by application logic.
Note that Oracle has declared Object.finalize() as deprecated since JDK 9.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodCall[pmd-java:matchesSig("java.lang.Object#finalize()")]
(: it's ok inside finalize :)
[not(SuperExpression and ancestor::*[self::MethodDeclaration or self::Initializer][1][@Name = 'finalize'][@Arity = 0][VoidType])]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
void foo() {
Bar b = new Bar();
b.finalize();
}
]]>
</example>
</rule>
<rule name="AvoidCatchingNPE"
language="java"
since="1.8"
message="Avoid catching NullPointerException; consider removing the cause of the NPE."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidcatchingnpe">
<description>
Code should never throw NullPointerExceptions under normal circumstances. A catch block may hide the
original error, causing other, more subtle problems later on.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//CatchClause/CatchParameter/ClassOrInterfaceType[pmd-java:typeIsExactly('java.lang.NullPointerException')]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
void bar() {
try {
// do something
} catch (NullPointerException npe) {
}
}
}
]]>
</example>
</rule>
<rule name="AvoidCatchingThrowable"
language="java"
since="1.2"
message="A catch statement should never catch throwable since it includes errors."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidcatchingthrowable">
<description>
Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as
OutOfMemoryError that should be exposed and managed separately.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value><![CDATA[
//CatchParameter[ClassOrInterfaceType[pmd-java:typeIsExactly('java.lang.Throwable')]]/VariableDeclaratorId
]]></value>
</property>
</properties>
<example>
<![CDATA[
public void bar() {
try {
// do something
} catch (Throwable th) { // should not catch Throwable
th.printStackTrace();
}
}
]]>
</example>
</rule>
<rule name="AvoidDecimalLiteralsInBigDecimalConstructor"
language="java"
since="3.4"
message="Avoid creating BigDecimal with a decimal (float/double) literal. Use a String literal"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoiddecimalliteralsinbigdecimalconstructor">
<description>
One might assume that the result of "new BigDecimal(0.1)" is exactly equal to 0.1, but it is actually
equal to .1000000000000000055511151231257827021181583404541015625.
This is because 0.1 cannot be represented exactly as a double (or as a binary fraction of any finite
length). Thus, the long value that is being passed in to the constructor is not exactly equal to 0.1,
appearances notwithstanding.
The (String) constructor, on the other hand, is perfectly predictable: 'new BigDecimal("0.1")' is
exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the
(String) constructor be used in preference to this one.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ConstructorCall[pmd-java:matchesSig('java.math.BigDecimal#new(double)')]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
BigDecimal bd = new BigDecimal(1.123); // loss of precision, this would trigger the rule
BigDecimal bd = new BigDecimal("1.123"); // preferred approach
BigDecimal bd = new BigDecimal(12); // preferred approach, ok for integer values
]]>
</example>
</rule>
<rule name="AvoidDuplicateLiterals"
language="java"
since="1.0"
message="The String literal {0} appears {1} times in this file; the first occurrence is on line {2}"
class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidDuplicateLiteralsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidduplicateliterals">
<description>
Code containing duplicate String literals can usually be improved by declaring the String as a constant field.
</description>
<priority>3</priority>
<example>
<![CDATA[
private void bar() {
buz("Howdy");
buz("Howdy");
buz("Howdy");
buz("Howdy");
}
private void buz(String x) {}
]]>
</example>
</rule>
<rule name="AvoidEnumAsIdentifier"
language="java"
maximumLanguageVersion="1.4"
since="3.4"
message="Avoid using enum as an identifier; it's a reserved word in JDK 1.5"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidenumasidentifier">
<description>
Use of the term `enum` will conflict with newer versions of Java since it is a reserved word.
Since Java 1.5, the token `enum` became a reserved word and using it as an identifier will
result in a compilation failure for Java 1.5 and later. This rule is therefore only useful
for old Java code before Java 1.5. It can be used to identify problematic code prior to a Java update.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>//VariableDeclaratorId[@Name='enum']</value>
</property>
</properties>
<example>
<![CDATA[
public class A {
public class Foo {
String enum = "foo";
}
}
]]>
</example>
</rule>
<rule name="AvoidFieldNameMatchingMethodName"
language="java"
since="3.0"
message="Field {0} has the same name as a method"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidfieldnamematchingmethodname">
<description>
It can be confusing to have a field name with the same name as a method. While this is permitted,
having information (field) and actions (method) is not clear naming. Developers versed in
Smalltalk often prefer this approach as the methods denote accessor methods.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//FieldDeclaration/VariableDeclarator/VariableDeclaratorId
[some $method in ../../..[self::ClassOrInterfaceBody or self::EnumBody]/MethodDeclaration
satisfies lower-case(@Name) = lower-case($method/@Name)]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
Object bar;
// bar is data or an action or both?
void bar() {
}
}
]]>
</example>
</rule>
<rule name="AvoidFieldNameMatchingTypeName"
language="java"
since="3.0"
message="It is somewhat confusing to have a field name matching the declaring class name"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidfieldnamematchingtypename">
<description>
It is somewhat confusing to have a field name matching the declaring type name.
This probably means that type and/or field names should be chosen more carefully.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//FieldDeclaration/VariableDeclarator/VariableDeclaratorId
[lower-case(@Name) = lower-case(ancestor::ClassOrInterfaceDeclaration[1]/@SimpleName)]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo extends Bar {
int foo; // There is probably a better name that can be used
}
public interface Operation {
int OPERATION = 1; // There is probably a better name that can be used
}
]]>
</example>
</rule>
<rule name="AvoidInstanceofChecksInCatchClause"
language="java"
since="3.0"
message="An instanceof check is being performed on the caught exception. Create a separate catch clause for this exception type."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidinstanceofchecksincatchclause">
<description>
Each caught exception type should be handled in its own catch clause.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//CatchParameter
/following-sibling::Block//InfixExpression[@Operator = 'instanceof']
/VariableAccess[@Name = ./ancestor::Block/preceding-sibling::CatchParameter/@Name]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
try { // Avoid this
// do something
} catch (Exception ee) {
if (ee instanceof IOException) {
cleanup();
}
}
try { // Prefer this:
// do something
} catch (IOException ee) {
cleanup();
}
]]>
</example>
</rule>
<rule name="AvoidLiteralsInIfCondition"
language="java"
since="4.2.6"
message="Avoid using literals in if statements"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidliteralsinifcondition">
<description>
Avoid using hard-coded literals in conditional statements. By declaring them as static variables
or private members with descriptive names maintainability is enhanced. By default, the literals "-1" and "0" are ignored.
More exceptions can be defined with the property "ignoreMagicNumbers".
The rule doesn't consider deeper expressions by default, but this can be enabled via the property `ignoreExpressions`.
With this property set to false, if-conditions like `i == 1 + 5` are reported as well. Note that in that case,
the property ignoreMagicNumbers is not taken into account, if there are multiple literals involved in such an expression.
</description>
<priority>3</priority>
<properties>
<property name="ignoreMagicNumbers"
description="Comma-separated list of magic numbers, that should be ignored"
type="String" value="-1,0"/>
<property name="ignoreExpressions"
description="If true, only literals in simple if conditions are considered. Otherwise literals in expressions are checked, too."
type="Boolean" value="true"/>
<property name="xpath">
<value>
<![CDATA[
(: simple case - no deep expressions - this is always executed :)
//IfStatement/*[1]/*[pmd-java:nodeIs('Literal')]
[not(pmd-java:nodeIs('NullLiteral'))]
[not(pmd-java:nodeIs('BooleanLiteral'))]
[empty(index-of(tokenize($ignoreMagicNumbers, '\s*,\s*'), @Image))]
|
(: consider also deeper expressions :)
//IfStatement[$ignoreExpressions = false()]/*[1]//*[not(self::UnaryExpression[@Operator = '-'])]/*[pmd-java:nodeIs('Literal')]
[not(pmd-java:nodeIs('NullLiteral'))]
[not(pmd-java:nodeIs('BooleanLiteral'))]
[empty(index-of(tokenize($ignoreMagicNumbers, '\s*,\s*'), @Image))]
|
(: consider negative literals :)
//IfStatement[$ignoreExpressions = false()]/*[1]//UnaryExpression[@Operator = '-']/*[pmd-java:nodeIs('Literal')]
[not(pmd-java:nodeIs('NullLiteral'))]
[not(pmd-java:nodeIs('BooleanLiteral'))]
[empty(index-of(tokenize($ignoreMagicNumbers, '\s*,\s*'), concat('-', @Image)))]
|
(: consider multiple literals in expressions :)
//IfStatement[$ignoreExpressions = false()]/*[1][count(*[pmd-java:nodeIs('Literal')]
[not(pmd-java:nodeIs('NullLiteral'))]
[not(pmd-java:nodeIs('BooleanLiteral'))]) > 1]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
private static final int MAX_NUMBER_OF_REQUESTS = 10;
public void checkRequests() {
if (i == 10) { // magic number, buried in a method
doSomething();
}
if (i == MAX_NUMBER_OF_REQUESTS) { // preferred approach
doSomething();
}
if (aString.indexOf('.') != -1) {} // magic number -1, by default ignored
if (aString.indexOf('.') >= 0) { } // alternative approach
if (aDouble > 0.0) {} // magic number 0.0
if (aDouble >= Double.MIN_VALUE) {} // preferred approach
// with rule property "ignoreExpressions" set to "false"
if (i == pos + 5) {} // violation: magic number 5 within an (additive) expression
if (i == pos + SUFFIX_LENGTH) {} // preferred approach
if (i == 5 && "none".equals(aString)) {} // 2 violations: magic number 5 and literal "none"
}
]]>
</example>
</rule>
<rule name="AvoidLosingExceptionInformation"
since="4.2.6"
language="java"
message="Avoid statements in a catch block that invoke accessors on the exception without using the information"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidlosingexceptioninformation">
<description>
Statements in a catch block that invoke accessors on the exception without using the information
only add to code size. Either remove the invocation, or use the return result.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//CatchClause/Block/ExpressionStatement/MethodCall[
pmd-java:matchesSig("java.lang.Throwable#getMessage()")
or pmd-java:matchesSig("java.lang.Throwable#getLocalizedMessage()")
or pmd-java:matchesSig("java.lang.Throwable#getCause()")
or pmd-java:matchesSig("java.lang.Throwable#getStackTrace()")
or pmd-java:matchesSig("java.lang.Object#toString()")
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public void bar() {
try {
// do something
} catch (SomeException se) {
se.getMessage();
}
}
]]>
</example>
</rule>
<rule name="AvoidMultipleUnaryOperators"
language="java"
since="4.2"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="Using multiple unary operators may be a bug, and/or is confusing."
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidmultipleunaryoperators">
<description>
The use of multiple unary operators may be problematic, and/or confusing.
Ensure that the intended usage is not a bug, or consider simplifying the expression.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value><![CDATA[
(: Only report on the toplevel one :)
//UnaryExpression[UnaryExpression and not(parent::UnaryExpression)]
]]></value>
</property>
</properties>
<example>
<![CDATA[
// These are typo bugs, or at best needlessly complex and confusing:
int i = - -1;
int j = + - +1;
int z = ~~2;
boolean b = !!true;
boolean c = !!!true;
// These are better:
int i = 1;
int j = -1;
int z = 2;
boolean b = true;
boolean c = false;
// And these just make your brain hurt:
int i = ~-2;
int j = -~7;
]]>
</example>
</rule>
<rule name="AvoidUsingOctalValues"
language="java"
since="3.9"
message="Do not start a literal by 0 unless it's an octal value"
class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidUsingOctalValuesRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidusingoctalvalues">
<description>
Integer literals should not start with zero since this denotes that the rest of literal will be
interpreted as an octal value.
</description>
<priority>3</priority>
<example>
<![CDATA[
int i = 012; // set i with 10 not 12
int j = 010; // set j with 8 not 10
k = i * j; // set k with 80 not 120
]]>
</example>
</rule>
<rule name="BeanMembersShouldSerialize" ref="NonSerializableClass" deprecated="true" />
<rule name="BrokenNullCheck"
language="java"
since="3.8"
message="This expression will throw a NullPointerException"
class="net.sourceforge.pmd.lang.java.rule.errorprone.BrokenNullCheckRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#brokennullcheck">
<description>
The null check is broken since it will throw a NullPointerException itself.
It is likely that you used || instead of && or vice versa.
</description>
<priority>2</priority>
<example>
<![CDATA[
public String bar(String string) {
// should be &&
if (string!=null || !string.equals(""))
return string;
// should be ||
if (string==null && string.equals(""))
return string;
}
]]>
</example>
</rule>
<rule name="CallSuperFirst"
since="4.2.5"
language="java"
message="super should be called at the start of the method"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#callsuperfirst">
<description>Super should be called at the start of the method</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration
[
pmd-java:typeIs('android.app.Activity') or
pmd-java:typeIs('android.app.Application') or
pmd-java:typeIs('android.app.Service')
]
//MethodDeclaration
[
@Name=('onCreate', 'onConfigurationChanged', 'onPostCreate', 'onPostResume', 'onRestart',
'onRestoreInstanceState', 'onResume', 'onStart')
]
[not(Block/*[1]/MethodCall[SuperExpression][@MethodName = ancestor::MethodDeclaration/@Name])]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
import android.app.Activity;
import android.os.Bundle;
public class DummyActivity extends Activity {
public void onCreate(Bundle bundle) {
// missing call to super.onCreate(bundle)
foo();
}
}
]]>
</example>
</rule>
<rule name="CallSuperLast"
since="4.2.5"
language="java"
message="super should be called at the end of the method"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#callsuperlast">
<description>
Super should be called at the end of the method
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration
[
pmd-java:typeIs('android.app.Activity') or
pmd-java:typeIs('android.app.Application') or
pmd-java:typeIs('android.app.Service')
]
//MethodDeclaration
[
@Name=('finish', 'onDestroy', 'onPause', 'onSaveInstanceState', 'onStop', 'onTerminate')
]
[not(Block/*[last()]/MethodCall[SuperExpression][@MethodName = ancestor::MethodDeclaration/@Name])]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
import android.app.Activity;
public class DummyActivity extends Activity {
public void onPause() {
foo();
// missing call to super.onPause()
}
}
]]>
</example>
</rule>
<rule name="CheckSkipResult"
language="java"
since="5.0"
message="Check the value returned by the skip() method of an InputStream to see if the requested number of bytes has been skipped."
class="net.sourceforge.pmd.lang.java.rule.errorprone.CheckSkipResultRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#checkskipresult">
<description>
The skip() method may skip a smaller number of bytes than requested. Check the returned value to find out if it was the case or not.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Foo {
private FileInputStream _s = new FileInputStream("file");
public void skip(int n) throws IOException {
_s.skip(n); // You are not sure that exactly n bytes are skipped
}
public void skipExactly(int n) throws IOException {
while (n != 0) {
long skipped = _s.skip(n);
if (skipped == 0)
throw new EOFException();
n -= skipped;
}
}
]]>
</example>
</rule>
<rule name="ClassCastExceptionWithToArray"
language="java"
since="3.4"
message="This usage of the Collection.toArray() method will throw a ClassCastException."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#classcastexceptionwithtoarray">
<description>
When deriving an array of a specific class from your Collection, one should provide an array of
the same class as the parameter of the `toArray()` method. Doing otherwise will result
in a `ClassCastException`.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//CastExpression[ArrayType/ClassOrInterfaceType[not(pmd-java:typeIsExactly('java.lang.Object'))]]
/MethodCall[pmd-java:matchesSig("java.util.Collection#toArray()")]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
Collection c = new ArrayList();
Integer obj = new Integer(1);
c.add(obj);
// this would trigger the rule (and throw a ClassCastException if executed)
Integer[] a = (Integer [])c.toArray();
// this is fine and will not trigger the rule
Integer[] b = (Integer [])c.toArray(new Integer[0]);
]]>
</example>
</rule>
<rule name="CloneMethodMustBePublic"
language="java"
since="5.4.0"
message="clone() method must be public if the class implements Cloneable"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#clonemethodmustbepublic">
<description>
The java manual says "By convention, classes that implement this interface should override
Object.clone (which is protected) with a public method."
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration[not(pmd-java:modifiers() = "public")]
[@Name = 'clone']
[@Arity = 0]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException { // Violation, must be public
}
}
public class Foo implements Cloneable {
@Override
protected Foo clone() { // Violation, must be public
}
}
public class Foo implements Cloneable {
@Override
public Object clone() // Ok
}
]]>
</example>
</rule>
<rule name="CloneMethodMustImplementCloneable"
language="java"
since="1.9"
message="clone() method should be implemented only if implementing Cloneable interface"
class="net.sourceforge.pmd.lang.java.rule.errorprone.CloneMethodMustImplementCloneableRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#clonemethodmustimplementcloneable">
<description>
The method clone() should only be implemented if the class implements the Cloneable interface with the exception of
a final method that only throws CloneNotSupportedException.
The rule can also detect, if the class implements or extends a Cloneable class.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class MyClass {
public Object clone() throws CloneNotSupportedException {
return foo;
}
}
]]>
</example>
</rule>
<rule name="CloneMethodReturnTypeMustMatchClassName"
language="java"
minimumLanguageVersion="1.5"
since="5.4.0"
message="The return type of the clone() method must be the class name when implements Cloneable"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#clonemethodreturntypemustmatchclassname">
<description>
If a class implements `Cloneable` the return type of the method `clone()` must be the class name. That way, the caller
of the clone method doesn't need to cast the returned clone to the correct type.
Note: Such a covariant return type is only possible with Java 1.5 or higher.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration
[@Name = 'clone']
[@Arity = 0]
[ClassOrInterfaceType[1]/@SimpleName != ancestor::ClassOrInterfaceDeclaration[1]/@SimpleName]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo implements Cloneable {
@Override
protected Object clone() { // Violation, Object must be Foo
}
}
public class Foo implements Cloneable {
@Override
public Foo clone() { //Ok
}
}
]]>
</example>
</rule>
<rule name="CloseResource"
language="java"
since="1.2.2"
message="Ensure that resources like this {0} object are closed after use"
class="net.sourceforge.pmd.lang.java.rule.errorprone.CloseResourceRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#closeresource">
<description>
Ensure that resources (like `java.sql.Connection`, `java.sql.Statement`, and `java.sql.ResultSet` objects
and any subtype of `java.lang.AutoCloseable`) are always closed after use.
Failing to do so might result in resource leaks.
Note: It suffices to configure the super type, e.g. `java.lang.AutoCloseable`, so that this rule automatically triggers
on any subtype (e.g. `java.io.FileInputStream`). Additionally specifying `java.sql.Connection` helps in detecting
the types, if the type resolution / auxclasspath is not correctly setup.
Note: Since PMD 6.16.0 the default value for the property `types` contains `java.lang.AutoCloseable` and detects
now cases where the standard `java.io.*Stream` classes are involved. In order to restore the old behaviour,
just remove "AutoCloseable" from the types.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Bar {
public void withSQL() {
Connection c = pool.getConnection();
try {
// do stuff
} catch (SQLException ex) {
// handle exception
} finally {
// oops, should close the connection using 'close'!
// c.close();