Solution for issue #816
Fixed the issue with traversing the tree and checking out if the getInstance method is used twice under the same class.
This commit is contained in:
@ -4,35 +4,58 @@
|
|||||||
|
|
||||||
package net.sourceforge.pmd.lang.java.rule.errorprone;
|
package net.sourceforge.pmd.lang.java.rule.errorprone;
|
||||||
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
|
import java.util.List;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
|
||||||
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
|
import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
|
||||||
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
|
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns Checks if the singleton rule is used properly.
|
||||||
|
*/
|
||||||
public class SingleMethodSingletonRule extends AbstractJavaRule {
|
public class SingleMethodSingletonRule extends AbstractJavaRule {
|
||||||
|
|
||||||
private Set<String> methodset = new HashSet<String>();
|
/**
|
||||||
|
* Checks for getInstance method usage in the same class.
|
||||||
|
* @param node of ASTCLass
|
||||||
|
* @param data of Object
|
||||||
|
* @return Object
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object visit(ASTCompilationUnit node, Object data) {
|
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
|
||||||
methodset.clear();
|
|
||||||
return super.visit(node, data);
|
String a = node.getImage(); // Get the name of the Class it's part of
|
||||||
|
System.out.println(a);
|
||||||
|
|
||||||
|
List<ASTMethodDeclaration> methods = node.findDescendantsOfType(ASTMethodDeclaration.class); // Find the name of methods in it
|
||||||
|
|
||||||
|
System.out.println(methods);
|
||||||
|
|
||||||
|
int count = 0;
|
||||||
|
for (ASTMethodDeclaration method : methods) {
|
||||||
|
|
||||||
|
System.out.println(method.getName());
|
||||||
|
if (method.getName().equals("getInstance")) {
|
||||||
|
count++;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object visit(ASTMethodDeclaration node, Object data) {
|
|
||||||
if (node.getResultType().isVoid()) {
|
|
||||||
return super.visit(node, data);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ("getInstance".equals(node.getMethodName())) {
|
if (count > 1) {
|
||||||
if (!methodset.add(node.getMethodName())) {
|
System.out.println("error");
|
||||||
addViolation(data, node);
|
addViolation(data, node);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/*
|
||||||
|
Can now check if each class has only one getInstance methods than it's all sorted.
|
||||||
|
*/
|
||||||
|
|
||||||
return super.visit(node, data);
|
return super.visit(node, data);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user