001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2026 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.Optional; 025import java.util.Set; 026import java.util.stream.Collectors; 027 028import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 029import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 030import com.puppycrawl.tools.checkstyle.api.DetailAST; 031import com.puppycrawl.tools.checkstyle.api.FullIdent; 032import com.puppycrawl.tools.checkstyle.api.TokenTypes; 033import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 034 035/** 036 * <div> 037 * Checks for illegal instantiations where a factory method is preferred. 038 * </div> 039 * 040 * <p> 041 * Rationale: Depending on the project, for some classes it might be 042 * preferable to create instances through factory methods rather than 043 * calling the constructor. 044 * </p> 045 * 046 * <p> 047 * A simple example is the {@code java.lang.Boolean} class. 048 * For performance reasons, it is preferable to use the predefined constants 049 * {@code TRUE} and {@code FALSE}. 050 * Constructor invocations should be replaced by calls to {@code Boolean.valueOf()}. 051 * </p> 052 * 053 * <p> 054 * Some extremely performance sensitive projects may require the use of factory 055 * methods for other classes as well, to enforce the usage of number caches or 056 * object pools. 057 * </p> 058 * 059 * <p> 060 * Notes: 061 * There is a limitation that it is currently not possible to specify array classes. 062 * </p> 063 * 064 * @since 3.0 065 */ 066@FileStatefulCheck 067public class IllegalInstantiationCheck 068 extends AbstractCheck { 069 070 /** 071 * A key is pointing to the warning message text in "messages.properties" 072 * file. 073 */ 074 public static final String MSG_KEY = "instantiation.avoid"; 075 076 /** {@link java.lang} package as string. */ 077 private static final String JAVA_LANG = "java.lang."; 078 079 /** The imports for the file. */ 080 private final Set<FullIdent> imports = new HashSet<>(); 081 082 /** The class names defined in the file. */ 083 private final Set<String> classNames = new HashSet<>(); 084 085 /** The instantiations in the file. */ 086 private final Set<DetailAST> instantiations = new HashSet<>(); 087 088 /** Specify fully qualified class names that should not be instantiated. */ 089 private Set<String> classes = new HashSet<>(); 090 091 /** Name of the package. */ 092 private String pkgName; 093 094 /** 095 * Creates a new {@code IllegalInstantiationCheck} instance. 096 */ 097 public IllegalInstantiationCheck() { 098 // no code by default 099 } 100 101 @Override 102 public int[] getDefaultTokens() { 103 return getRequiredTokens(); 104 } 105 106 @Override 107 public int[] getAcceptableTokens() { 108 return getRequiredTokens(); 109 } 110 111 @Override 112 public int[] getRequiredTokens() { 113 return new int[] { 114 TokenTypes.IMPORT, 115 TokenTypes.LITERAL_NEW, 116 TokenTypes.PACKAGE_DEF, 117 TokenTypes.CLASS_DEF, 118 }; 119 } 120 121 @Override 122 public void beginTree(DetailAST rootAST) { 123 pkgName = null; 124 imports.clear(); 125 instantiations.clear(); 126 classNames.clear(); 127 } 128 129 @Override 130 public void visitToken(DetailAST ast) { 131 switch (ast.getType()) { 132 case TokenTypes.LITERAL_NEW -> processLiteralNew(ast); 133 case TokenTypes.PACKAGE_DEF -> processPackageDef(ast); 134 case TokenTypes.IMPORT -> processImport(ast); 135 case TokenTypes.CLASS_DEF -> processClassDef(ast); 136 default -> throw new IllegalArgumentException("Unknown type " + ast); 137 } 138 } 139 140 @Override 141 public void finishTree(DetailAST rootAST) { 142 instantiations.forEach(this::postProcessLiteralNew); 143 } 144 145 /** 146 * Collects classes defined in the source file. Required 147 * to avoid false alarms for local vs. java.lang classes. 148 * 149 * @param ast the class def token. 150 */ 151 private void processClassDef(DetailAST ast) { 152 final DetailAST identToken = ast.findFirstToken(TokenTypes.IDENT); 153 final String className = identToken.getText(); 154 classNames.add(className); 155 } 156 157 /** 158 * Perform processing for an import token. 159 * 160 * @param ast the import token 161 */ 162 private void processImport(DetailAST ast) { 163 final FullIdent name = FullIdent.createFullIdentBelow(ast); 164 // Note: different from UnusedImportsCheck.processImport(), 165 // '.*' imports are also added here 166 imports.add(name); 167 } 168 169 /** 170 * Perform processing for an package token. 171 * 172 * @param ast the package token 173 */ 174 private void processPackageDef(DetailAST ast) { 175 final DetailAST packageNameAST = ast.getLastChild() 176 .getPreviousSibling(); 177 final FullIdent packageIdent = 178 FullIdent.createFullIdent(packageNameAST); 179 pkgName = packageIdent.getText(); 180 } 181 182 /** 183 * Collects a "new" token. 184 * 185 * @param ast the "new" token 186 */ 187 private void processLiteralNew(DetailAST ast) { 188 if (ast.getParent().getType() != TokenTypes.METHOD_REF) { 189 instantiations.add(ast); 190 } 191 } 192 193 /** 194 * Processes one of the collected "new" tokens when walking tree 195 * has finished. 196 * 197 * @param newTokenAst the "new" token. 198 */ 199 private void postProcessLiteralNew(DetailAST newTokenAst) { 200 final DetailAST typeNameAst = newTokenAst.getFirstChild(); 201 final DetailAST 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 String fqClassName = getIllegalInstantiation(typeName); 207 if (fqClassName != null) { 208 log(newTokenAst, MSG_KEY, fqClassName); 209 } 210 } 211 } 212 213 /** 214 * Checks illegal instantiations. 215 * 216 * @param className instantiated class, may or may not be qualified 217 * @return the fully qualified class name of className 218 * or null if instantiation of className is OK 219 */ 220 private String getIllegalInstantiation(String className) { 221 final String fullClassName; 222 223 if (classes.contains(className)) { 224 fullClassName = className; 225 } 226 else { 227 final Optional<String> importResult = checkImportStatements(className); 228 if (importResult.isPresent()) { 229 fullClassName = importResult.get(); 230 } 231 else { 232 final int pkgNameLen; 233 234 if (pkgName == null) { 235 pkgNameLen = 0; 236 } 237 else { 238 pkgNameLen = pkgName.length(); 239 } 240 241 fullClassName = classes.stream() 242 .filter(illegal -> { 243 return isSamePackage(className, pkgNameLen, illegal) 244 || isStandardClass(className, illegal); 245 }) 246 .findFirst() 247 .orElse(null); 248 } 249 } 250 return fullClassName; 251 } 252 253 /** 254 * Check import statements. 255 * 256 * @param className name of the class 257 * @return Optional containing value of illegal instantiated type, if found 258 */ 259 private Optional<String> checkImportStatements(String className) { 260 Optional<String> result = Optional.empty(); 261 for (FullIdent importLineText : imports) { 262 String importArg = importLineText.getText(); 263 if (importArg.endsWith(".*")) { 264 importArg = importArg.substring(0, importArg.length() - 1) 265 + className; 266 } 267 if (CommonUtil.baseClassName(importArg).equals(className) 268 && classes.contains(importArg)) { 269 result = Optional.of(importArg); 270 break; 271 } 272 } 273 return result; 274 } 275 276 /** 277 * Check that type is of the same package. 278 * 279 * @param className class name 280 * @param pkgNameLen package name 281 * @param illegal illegal value 282 * @return true if type of the same package 283 */ 284 private boolean isSamePackage(String className, int pkgNameLen, String illegal) { 285 // class from same package 286 287 // the top level package (pkgName == null) is covered by the 288 // "illegalInstances.contains(className)" check above 289 290 // the test is the "no garbage" version of 291 // illegal.equals(pkgName + "." + className) 292 return pkgName != null 293 && className.length() == illegal.length() - pkgNameLen - 1 294 && illegal.charAt(pkgNameLen) == '.' 295 && illegal.endsWith(className) 296 && illegal.startsWith(pkgName); 297 } 298 299 /** 300 * Is Standard Class. 301 * 302 * @param className class name 303 * @param illegal illegal value 304 * @return true if type is standard 305 */ 306 private boolean isStandardClass(String className, String illegal) { 307 boolean isStandardClass = false; 308 // class from java.lang 309 if (illegal.length() - JAVA_LANG.length() == className.length() 310 && illegal.endsWith(className) 311 && illegal.startsWith(JAVA_LANG)) { 312 // java.lang needs no import, but a class without import might 313 // also come from the same file or be in the same package. 314 // E.g. if a class defines an inner class "Boolean", 315 // the expression "new Boolean()" refers to that class, 316 // not to java.lang.Boolean 317 318 final boolean isSameFile = classNames.contains(className); 319 320 if (!isSameFile) { 321 isStandardClass = true; 322 } 323 } 324 return isStandardClass; 325 } 326 327 /** 328 * Setter to specify fully qualified class names that should not be instantiated. 329 * 330 * @param names class names 331 * @since 3.0 332 */ 333 public void setClasses(String... names) { 334 classes = Arrays.stream(names).collect(Collectors.toUnmodifiableSet()); 335 } 336 337}