KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mycompany > checks > MethodLimitCheck


1 package com.mycompany.checks;
2
3 import com.puppycrawl.tools.checkstyle.api.*;
4
5 public class MethodLimitCheck extends Check
6 {
7     /** the maximum number of methods per class/interface */
8     private int max = 30;
9
10     /**
11      * Give user a chance to configure max in the config file.
12      * @param aMax the user specified maximum parsed from configuration property.
13      */

14     public void setMax(int aMax)
15     {
16         max = aMax;
17     }
18
19     /**
20      * We are interested in CLASS_DEF and INTERFACE_DEF Tokens.
21      * @see Check
22      */

23     public int[] getDefaultTokens()
24     {
25         return new int[]{TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF};
26     }
27
28     /**
29      * @see Check
30      */

31     public void visitToken(DetailAST ast)
32     {
33         // the tree below a CLASS_DEF/INTERFACE_DEF looks like this:
34

35         // CLASS_DEF
36
// MODIFIERS
37
// class name (IDENT token type)
38
// EXTENDS_CLAUSE
39
// IMPLEMENTS_CLAUSE
40
// OBJBLOCK
41
// {
42
// some other stuff like variable declarations etc.
43
// METHOD_DEF
44
// more stuff, the users might mix methods, variables, etc.
45
// METHOD_DEF
46
// ...and so on
47
// }
48

49         // We use helper methods to navigate in the syntax tree
50

51         // find the OBJBLOCK node below the CLASS_DEF/INTERFACE_DEF
52
DetailAST objBlock = ast.findFirstToken(TokenTypes.OBJBLOCK);
53
54         // count the number of direct children of the OBJBLOCK
55
// that are METHOD_DEFS
56
int methodDefs = objBlock.getChildCount(TokenTypes.METHOD_DEF);
57
58         // report error if limit is reached
59
if (methodDefs > max) {
60             log(ast.getLineNo(), "too.many.methods", new Integer JavaDoc(max));
61         }
62     }
63 }
64
Popular Tags