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 package com.qulice.checkstyle;
32
33 import com.google.common.collect.Lists;
34 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
35 import com.puppycrawl.tools.checkstyle.api.DetailAST;
36 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
37 import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
38 import java.util.List;
39
40
41
42
43
44
45
46 public final class ProtectedMethodInFinalClassCheck extends AbstractCheck {
47
48 @Override
49 public int[] getDefaultTokens() {
50 return new int[] {
51 TokenTypes.CLASS_DEF,
52 };
53 }
54
55 @Override
56 public int[] getAcceptableTokens() {
57 return this.getDefaultTokens();
58 }
59
60 @Override
61 public int[] getRequiredTokens() {
62 return this.getDefaultTokens();
63 }
64
65 @Override
66 public void visitToken(final DetailAST ast) {
67 if (ast.getType() == TokenTypes.CLASS_DEF) {
68 final DetailAST modifiers = ast.findFirstToken(
69 TokenTypes.MODIFIERS
70 );
71 if (modifiers.findFirstToken(TokenTypes.FINAL) != null) {
72 this.checkMethods(ast);
73 }
74 }
75 }
76
77
78
79
80
81 private void checkMethods(final DetailAST ast) {
82 final DetailAST objblock = ast.findFirstToken(TokenTypes.OBJBLOCK);
83 for (final DetailAST method
84 : ProtectedMethodInFinalClassCheck.findAllChildren(
85 objblock, TokenTypes.METHOD_DEF
86 )
87 ) {
88 if (method
89 .findFirstToken(TokenTypes.MODIFIERS)
90 .findFirstToken(TokenTypes.LITERAL_PROTECTED) != null) {
91 if (AnnotationUtil.containsAnnotation(method, "Override")) {
92 this.log(
93 method.getLineNo(),
94 "Protected method is overriding default scoped method"
95 );
96 } else {
97 this.log(
98 method.getLineNo(),
99 "Final class should not contain protected methods"
100 );
101 }
102 }
103 }
104 }
105
106
107
108
109
110
111
112 private static Iterable<DetailAST> findAllChildren(final DetailAST base,
113 final int type) {
114 final List<DetailAST> children = Lists.newArrayList();
115 DetailAST child = base.getFirstChild();
116 while (child != null) {
117 if (child.getType() == type) {
118 children.add(child);
119 }
120 child = child.getNextSibling();
121 }
122 return children;
123 }
124 }