1 package com.puppycrawl.tools.checkstyle.checks.coding; 20 21 import java.util.HashSet ; 22 import java.util.Iterator ; 23 import java.util.Set ; 24 25 import com.puppycrawl.tools.checkstyle.api.Check; 26 import com.puppycrawl.tools.checkstyle.api.DetailAST; 27 import com.puppycrawl.tools.checkstyle.api.FullIdent; 28 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 29 import com.puppycrawl.tools.checkstyle.checks.CheckUtils; 30 31 46 public class CovariantEqualsCheck extends Check 47 { 48 49 private final Set mEqualsMethods = new HashSet (); 50 51 52 public int[] getDefaultTokens() 53 { 54 return new int[] {TokenTypes.CLASS_DEF, TokenTypes.LITERAL_NEW, }; 55 } 56 57 58 public int[] getRequiredTokens() 59 { 60 return getDefaultTokens(); 61 } 62 63 64 public void visitToken(DetailAST aAST) 65 { 66 mEqualsMethods.clear(); 67 boolean hasEqualsObject = false; 68 69 final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK); 71 if (objBlock != null) { 72 DetailAST child = (DetailAST) objBlock.getFirstChild(); 73 while (child != null) { 74 if (child.getType() == TokenTypes.METHOD_DEF) { 75 if (CheckUtils.isEqualsMethod(child)) { 76 if (hasObjectParameter(child)) { 77 hasEqualsObject = true; 78 } 79 else { 80 mEqualsMethods.add(child); 81 } 82 } 83 } 84 child = (DetailAST) child.getNextSibling(); 85 } 86 87 if (!hasEqualsObject) { 89 final Iterator it = mEqualsMethods.iterator(); 90 while (it.hasNext()) { 91 final DetailAST equalsAST = (DetailAST) it.next(); 92 final DetailAST nameNode = 93 equalsAST.findFirstToken(TokenTypes.IDENT); 94 log( 95 nameNode.getLineNo(), 96 nameNode.getColumnNo(), 97 "covariant.equals"); 98 } 99 } 100 } 101 } 102 103 110 private boolean hasObjectParameter(DetailAST aAST) 111 { 112 final DetailAST paramsNode = aAST.findFirstToken(TokenTypes.PARAMETERS); 114 if (paramsNode.getChildCount() != 1) { 115 return false; 116 } 117 118 final DetailAST paramNode = 120 paramsNode.findFirstToken(TokenTypes.PARAMETER_DEF); 121 final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE); 122 final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode); 123 final String name = fullIdent.getText(); 124 return (name.equals("Object") || name.equals("java.lang.Object")); 125 } 126 } 127 | Popular Tags |