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:
Akshat Bahety
2018-04-23 02:08:16 +05:30
committed by GitHub
parent 855d528563
commit 1a51582963

View File

@ -4,35 +4,58 @@
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.rule.AbstractJavaRule;
/**
* Returns Checks if the singleton rule is used properly.
*/
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) {
methodset.clear();
return super.visit(node, data);
}
@Override
public Object visit(ASTMethodDeclaration node, Object data) {
if (node.getResultType().isVoid()) {
return super.visit(node, data);
}
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
if ("getInstance".equals(node.getMethodName())) {
if (!methodset.add(node.getMethodName())) {
addViolation(data, node);
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++;
}
}
if (count > 1) {
System.out.println("error");
addViolation(data, node);
}
/*
Can now check if each class has only one getInstance methods than it's all sorted.
*/
return super.visit(node, data);
}
}