View Javadoc
1   /*xml
2   <module name="Checker">
3     <module name="TreeWalker">
4       <module name="UnnecessaryNullCheckWithInstanceOf"/>
5     </module>
6   </module>
7   */
8   package com.puppycrawl.tools.checkstyle.checks.coding.unnecessarynullcheckwithinstanceof;
9   
10  import java.util.ArrayList;
11  import java.util.List;
12  
13  // xdoc section -- start
14  public class Example1 {
15  
16    public void methodWithUnnecessaryNullCheck1(Object obj) {
17      // violation below, 'Unnecessary nullity check'
18      if (obj != null && obj instanceof String) {
19        String str = (String) obj;
20      }
21      if (obj instanceof String) {
22        String str = (String) obj;
23      }
24      // violation below, 'Unnecessary nullity check'
25      boolean isInvalid = obj != null && obj instanceof String;
26  
27      boolean isValid = obj instanceof String;
28    }
29    interface Validator {
30      boolean validate(Object obj);
31    }
32    public void anonymousClassImplementation() {
33      Validator v = new Validator() {
34        @Override
35        public boolean validate(Object obj) {
36          // violation below, 'Unnecessary nullity check'
37          return obj != null && obj instanceof String;
38        }
39      };
40    }
41    private final List<Object> objects = new ArrayList<>();
42  
43    public String basicTernary(Object obj) {
44      // violation below, 'Unnecessary nullity check'
45      return obj != null && obj instanceof String ? ((String) obj) : "";
46    }
47  
48    public String basicValidTernary(Object obj) {
49      return obj instanceof String ? ((String) obj) : "";
50    }
51    public void methodWithValidNullCheck(Object obj) {
52      if (obj != null) {
53        CharSequence cs = (CharSequence) obj;
54      }
55    }
56  }
57  // xdoc section -- end