Search code examples
javapmd

Is there a tool for reporting downcasts in Java?


Wondering if there is a reporting tool (such as PMD) which reports downcasting in Java code.


Solution

  • Catching all casts is easy with a custom PMD rule:

    import net.sourceforge.pmd.AbstractJavaRule;
    import net.sourceforge.pmd.ast.ASTCastExpression;
    
    public class CastRule extends AbstractJavaRule {
    
        public CastRule() {
        }
    
        @Override
        public Object visit(final ASTCastExpression node, final Object data) {
            addViolation(data, node);
            return super.visit(node, data);
        }
    }
    

    Unfortunately it catches upcasts too if they are explicit upcasts. Some example:

    final Number myNumber = 5;
    final Integer myInteger = (Integer) myNumber; // catched
    
    final Number myNumber2 = (Number) myInteger; // catched
    final Number myNumber3 = myInteger; // NOT catched
    

    Catching only downcasts looks rather complicated with PMD.

    Check this answer too, it contains some details about the usage.