ForbidInstantiationCheck extends AbstractCheck { @Override public void visitToken(DetailAST ast) { switch (ast.getType()) { case TokenTypes.IMPORT: importsList.add(getText(ast)); break; case TokenTypes.LITERAL_NEW: final String instanceClass = getText(ast); if (instanceClass != null) { final String instanceClassName = getClassName(instanceClass); for (String forbiddenClass : forbiddenClasses) { if (forbiddenClass.startsWith("java.lang.") && forbiddenClass.endsWith(instanceClassName)) { log(ast, MSG_KEY, instanceClassName); } else if (instanceClass.contains(PATH_SEPARATOR)) { if (instanceClass.equals(forbiddenClass)) { log(ast, MSG_KEY, instanceClassName); } } else if (addedUsingForbiddenImport(instanceClass, forbiddenClass)) { log(ast, MSG_KEY, instanceClass); } } } break; default: SevntuUtil.reportInvalidToken(ast.getType()); break; } } ForbidInstantiationCheck(); void setForbiddenClasses(final String... classNames); @Override void beginTree(final DetailAST rootAST); @Override int[] getDefaultTokens(); @Override int[] getAcceptableTokens(); @Override int[] getRequiredTokens(); @Override void visitToken(DetailAST ast); static final String MSG_KEY; }
@Test public void testUnsupportedNode() { final DetailAstImpl sync = new DetailAstImpl(); sync.setType(TokenTypes.LITERAL_SYNCHRONIZED); try { final ForbidInstantiationCheck check = new ForbidInstantiationCheck(); check.visitToken(sync); fail("exception expected"); } catch (IllegalArgumentException ex) { Assert.assertEquals("Found unsupported token: LITERAL_SYNCHRONIZED", ex.getMessage()); } }