
org.sonar.java.checks.naming.MethodNameSameAsClassCheck Maven / Gradle / Ivy
The newest version!
/*
* SonarQube Java
* Copyright (C) 2012-2025 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks.naming;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.tree.BaseTreeVisitor;
import org.sonar.plugins.java.api.tree.ClassTree;
import org.sonar.plugins.java.api.tree.IdentifierTree;
import org.sonar.plugins.java.api.tree.MethodTree;
import org.sonar.plugins.java.api.tree.Tree;
@Rule(key = "S1223")
public class MethodNameSameAsClassCheck extends BaseTreeVisitor implements JavaFileScanner {
private JavaFileScannerContext context;
@Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
scan(context.getTree());
}
@Override
public void visitClass(ClassTree tree) {
super.visitClass(tree);
IdentifierTree classSimpleName = tree.simpleName();
if (classSimpleName == null) {
return;
}
String className = classSimpleName.name();
for (Tree member : tree.members()) {
if (member.is(Tree.Kind.METHOD)) {
IdentifierTree simpleName = ((MethodTree) member).simpleName();
if (className.equals(simpleName.name())) {
context.reportIssue(this, simpleName, "Rename this method to prevent any misunderstanding or make it a constructor.");
}
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy