1 package net.sourceforge.pmd.lang.java.rule.basic; 2 3 import java.math.BigDecimal; 4 import java.math.BigInteger; 5 6 import net.sourceforge.pmd.RuleContext; 7 import net.sourceforge.pmd.lang.LanguageVersion; 8 import net.sourceforge.pmd.lang.ast.Node; 9 import net.sourceforge.pmd.lang.java.ast.ASTAllocationExpression; 10 import net.sourceforge.pmd.lang.java.ast.ASTArguments; 11 import net.sourceforge.pmd.lang.java.ast.ASTArrayDimsAndInits; 12 import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType; 13 import net.sourceforge.pmd.lang.java.ast.ASTLiteral; 14 import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; 15 import net.sourceforge.pmd.lang.java.typeresolution.TypeHelper; 16 17 public class BigIntegerInstantiationRule extends AbstractJavaRule { 18 19 @Override 20 public Object visit(ASTAllocationExpression node, Object data) { 21 Node type = node.jjtGetChild(0); 22 23 if (!(type instanceof ASTClassOrInterfaceType)) { 24 return super.visit(node, data); 25 } 26 27 boolean jdk15 = ((RuleContext) data).getLanguageVersion().compareTo(LanguageVersion.JAVA_15) >= 0; 28 if ((TypeHelper.isA((ASTClassOrInterfaceType) type, BigInteger.class) || jdk15 && TypeHelper.isA((ASTClassOrInterfaceType) type, BigDecimal.class)) && 29 !node.hasDescendantOfType(ASTArrayDimsAndInits.class) 30 ) { 31 ASTArguments args = node.getFirstChildOfType(ASTArguments.class); 32 if (args.getArgumentCount() == 1) { 33 ASTLiteral literal = node.getFirstDescendantOfType(ASTLiteral.class); 34 if (literal == null || literal.jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent().jjtGetParent() != args) { 35 return super.visit(node, data); 36 } 37 38 String img = literal.getImage(); 39 if (literal.isStringLiteral()) { 40 img = img.substring(1, img.length() - 1); 41 } 42 43 if ("0".equals(img) || "1".equals(img) || jdk15 && "10".equals(img)) { 44 addViolation(data, node); 45 return data; 46 } 47 } 48 } 49 return super.visit(node, data); 50 } 51 52 }