The Analysis of the following Java code causes ClassCastException in PrematureDeclarationRule:
int switchvar = 0;
switch (switchvar) {
case 1:
boolean localvar;
break;
case 2:
localvar = false;
if (localvar) {
//
}
}
Result:
Exception applying rule PrematureDeclaration on file pmdtest\PmdSwitchBug.java, continuing with next rule
java.lang.ClassCastException: net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel cannot be cast to net.sourceforge.pmd.lang.java.ast.ASTBlockStatement
at net.sourceforge.pmd.lang.java.rule.optimizations.PrematureDeclarationRule.visit(PrematureDeclarationRule.java:57)
at net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration.jjtAccept(ASTLocalVariableDeclaration.java:25)
The reason is the declaration of a variable inside a switch statement and its reuse in another case.
Irrespective of this bug it's worth considering the reuse of a local variable in another case block questionable and add a corresponding PMD rule.
The attachment contains a Eclipse Java project that can be used as test case. PMD is invoked using an Ant script.