001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2017 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018//////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.coding; 021 022import java.util.Arrays; 023import java.util.HashSet; 024import java.util.Set; 025import java.util.stream.Collectors; 026 027import antlr.collections.AST; 028import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 029import com.puppycrawl.tools.checkstyle.api.DetailAST; 030import com.puppycrawl.tools.checkstyle.api.FullIdent; 031import com.puppycrawl.tools.checkstyle.api.TokenTypes; 032import com.puppycrawl.tools.checkstyle.utils.CommonUtils; 033 034/** 035 * <p> 036 * Checks for illegal instantiations where a factory method is preferred. 037 * </p> 038 * <p> 039 * Rationale: Depending on the project, for some classes it might be 040 * preferable to create instances through factory methods rather than 041 * calling the constructor. 042 * </p> 043 * <p> 044 * A simple example is the java.lang.Boolean class, to save memory and CPU 045 * cycles it is preferable to use the predefined constants TRUE and FALSE. 046 * Constructor invocations should be replaced by calls to Boolean.valueOf(). 047 * </p> 048 * <p> 049 * Some extremely performance sensitive projects may require the use of factory 050 * methods for other classes as well, to enforce the usage of number caches or 051 * object pools. 052 * </p> 053 * <p> 054 * Limitations: It is currently not possible to specify array classes. 055 * </p> 056 * <p> 057 * An example of how to configure the check is: 058 * </p> 059 * <pre> 060 * <module name="IllegalInstantiation"/> 061 * </pre> 062 * @author lkuehne 063 */ 064public class IllegalInstantiationCheck 065 extends AbstractCheck { 066 067 /** 068 * A key is pointing to the warning message text in "messages.properties" 069 * file. 070 */ 071 public static final String MSG_KEY = "instantiation.avoid"; 072 073 /** {@link java.lang} package as string */ 074 private static final String JAVA_LANG = "java.lang."; 075 076 /** The imports for the file. */ 077 private final Set<FullIdent> imports = new HashSet<>(); 078 079 /** The class names defined in the file. */ 080 private final Set<String> classNames = new HashSet<>(); 081 082 /** The instantiations in the file. */ 083 private final Set<DetailAST> instantiations = new HashSet<>(); 084 085 /** Set of fully qualified class names. E.g. "java.lang.Boolean" */ 086 private Set<String> illegalClasses = new HashSet<>(); 087 088 /** Name of the package. */ 089 private String pkgName; 090 091 @Override 092 public int[] getDefaultTokens() { 093 return getAcceptableTokens(); 094 } 095 096 @Override 097 public int[] getAcceptableTokens() { 098 return new int[] { 099 TokenTypes.IMPORT, 100 TokenTypes.LITERAL_NEW, 101 TokenTypes.PACKAGE_DEF, 102 TokenTypes.CLASS_DEF, 103 }; 104 } 105 106 @Override 107 public int[] getRequiredTokens() { 108 return new int[] { 109 TokenTypes.IMPORT, 110 TokenTypes.LITERAL_NEW, 111 TokenTypes.PACKAGE_DEF, 112 }; 113 } 114 115 @Override 116 public void beginTree(DetailAST rootAST) { 117 super.beginTree(rootAST); 118 pkgName = null; 119 imports.clear(); 120 instantiations.clear(); 121 classNames.clear(); 122 } 123 124 @Override 125 public void visitToken(DetailAST ast) { 126 switch (ast.getType()) { 127 case TokenTypes.LITERAL_NEW: 128 processLiteralNew(ast); 129 break; 130 case TokenTypes.PACKAGE_DEF: 131 processPackageDef(ast); 132 break; 133 case TokenTypes.IMPORT: 134 processImport(ast); 135 break; 136 case TokenTypes.CLASS_DEF: 137 processClassDef(ast); 138 break; 139 default: 140 throw new IllegalArgumentException("Unknown type " + ast); 141 } 142 } 143 144 @Override 145 public void finishTree(DetailAST rootAST) { 146 instantiations.forEach(this::postProcessLiteralNew); 147 } 148 149 /** 150 * Collects classes defined in the source file. Required 151 * to avoid false alarms for local vs. java.lang classes. 152 * 153 * @param ast the class def token. 154 */ 155 private void processClassDef(DetailAST ast) { 156 final DetailAST identToken = ast.findFirstToken(TokenTypes.IDENT); 157 final String className = identToken.getText(); 158 classNames.add(className); 159 } 160 161 /** 162 * Perform processing for an import token. 163 * @param ast the import token 164 */ 165 private void processImport(DetailAST ast) { 166 final FullIdent name = FullIdent.createFullIdentBelow(ast); 167 // Note: different from UnusedImportsCheck.processImport(), 168 // '.*' imports are also added here 169 imports.add(name); 170 } 171 172 /** 173 * Perform processing for an package token. 174 * @param ast the package token 175 */ 176 private void processPackageDef(DetailAST ast) { 177 final DetailAST packageNameAST = ast.getLastChild() 178 .getPreviousSibling(); 179 final FullIdent packageIdent = 180 FullIdent.createFullIdent(packageNameAST); 181 pkgName = packageIdent.getText(); 182 } 183 184 /** 185 * Collects a "new" token. 186 * @param ast the "new" token 187 */ 188 private void processLiteralNew(DetailAST ast) { 189 if (ast.getParent().getType() != TokenTypes.METHOD_REF) { 190 instantiations.add(ast); 191 } 192 } 193 194 /** 195 * Processes one of the collected "new" tokens when walking tree 196 * has finished. 197 * @param newTokenAst the "new" token. 198 */ 199 private void postProcessLiteralNew(DetailAST newTokenAst) { 200 final DetailAST typeNameAst = newTokenAst.getFirstChild(); 201 final AST nameSibling = typeNameAst.getNextSibling(); 202 if (nameSibling.getType() != TokenTypes.ARRAY_DECLARATOR) { 203 // ast != "new Boolean[]" 204 final FullIdent typeIdent = FullIdent.createFullIdent(typeNameAst); 205 final String typeName = typeIdent.getText(); 206 final int lineNo = newTokenAst.getLineNo(); 207 final int colNo = newTokenAst.getColumnNo(); 208 final String fqClassName = getIllegalInstantiation(typeName); 209 if (fqClassName != null) { 210 log(lineNo, colNo, MSG_KEY, fqClassName); 211 } 212 } 213 } 214 215 /** 216 * Checks illegal instantiations. 217 * @param className instantiated class, may or may not be qualified 218 * @return the fully qualified class name of className 219 * or null if instantiation of className is OK 220 */ 221 private String getIllegalInstantiation(String className) { 222 String fullClassName = null; 223 224 if (illegalClasses.contains(className)) { 225 fullClassName = className; 226 } 227 else { 228 final int pkgNameLen; 229 230 if (pkgName == null) { 231 pkgNameLen = 0; 232 } 233 else { 234 pkgNameLen = pkgName.length(); 235 } 236 237 for (String illegal : illegalClasses) { 238 if (isStandardClass(className, illegal) 239 || isSamePackage(className, pkgNameLen, illegal)) { 240 fullClassName = illegal; 241 } 242 else { 243 fullClassName = checkImportStatements(className); 244 } 245 246 if (fullClassName != null) { 247 break; 248 } 249 } 250 } 251 return fullClassName; 252 } 253 254 /** 255 * Check import statements. 256 * @param className name of the class 257 * @return value of illegal instantiated type 258 * @noinspection StringContatenationInLoop 259 */ 260 private String checkImportStatements(String className) { 261 String illegalType = null; 262 // import statements 263 for (FullIdent importLineText : imports) { 264 String importArg = importLineText.getText(); 265 if (importArg.endsWith(".*")) { 266 importArg = importArg.substring(0, importArg.length() - 1) 267 + className; 268 } 269 if (CommonUtils.baseClassName(importArg).equals(className) 270 && illegalClasses.contains(importArg)) { 271 illegalType = importArg; 272 break; 273 } 274 } 275 return illegalType; 276 } 277 278 /** 279 * Check that type is of the same package. 280 * @param className class name 281 * @param pkgNameLen package name 282 * @param illegal illegal value 283 * @return true if type of the same package 284 */ 285 private boolean isSamePackage(String className, int pkgNameLen, String illegal) { 286 // class from same package 287 288 // the top level package (pkgName == null) is covered by the 289 // "illegalInstances.contains(className)" check above 290 291 // the test is the "no garbage" version of 292 // illegal.equals(pkgName + "." + className) 293 return pkgName != null 294 && className.length() == illegal.length() - pkgNameLen - 1 295 && illegal.charAt(pkgNameLen) == '.' 296 && illegal.endsWith(className) 297 && illegal.startsWith(pkgName); 298 } 299 300 /** 301 * Is class of the same package. 302 * @param className class name 303 * @return true if same package class 304 */ 305 private boolean isSamePackage(String className) { 306 boolean isSamePackage = false; 307 try { 308 final ClassLoader classLoader = getClassLoader(); 309 if (classLoader != null) { 310 final String fqName = pkgName + "." + className; 311 classLoader.loadClass(fqName); 312 // no ClassNotFoundException, fqName is a known class 313 isSamePackage = true; 314 } 315 } 316 catch (final ClassNotFoundException ignored) { 317 // not a class from the same package 318 isSamePackage = false; 319 } 320 return isSamePackage; 321 } 322 323 /** 324 * Is Standard Class. 325 * @param className class name 326 * @param illegal illegal value 327 * @return true if type is standard 328 */ 329 private boolean isStandardClass(String className, String illegal) { 330 // class from java.lang 331 if (illegal.length() - JAVA_LANG.length() == className.length() 332 && illegal.endsWith(className) 333 && illegal.startsWith(JAVA_LANG)) { 334 // java.lang needs no import, but a class without import might 335 // also come from the same file or be in the same package. 336 // E.g. if a class defines an inner class "Boolean", 337 // the expression "new Boolean()" refers to that class, 338 // not to java.lang.Boolean 339 340 final boolean isSameFile = classNames.contains(className); 341 final boolean isSamePackage = isSamePackage(className); 342 343 if (!isSameFile && !isSamePackage) { 344 return true; 345 } 346 } 347 return false; 348 } 349 350 /** 351 * Sets the classes that are illegal to instantiate. 352 * @param names a comma separate list of class names 353 */ 354 public void setClasses(String... names) { 355 illegalClasses = Arrays.stream(names).collect(Collectors.toSet()); 356 } 357}