Skip to content

Commit

Permalink
Skip constructor and serialVersionUID field in the unused checker
Browse files Browse the repository at this point in the history
  • Loading branch information
testforstephen committed Aug 30, 2024
1 parent b57a9ed commit 6b671dd
Showing 1 changed file with 15 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type.JCPrimitiveType;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCImport;
Expand Down Expand Up @@ -159,11 +160,11 @@ private boolean isPrivateDeclaration(Tree tree) {
if (tree instanceof JCClassDecl classTree) {
return (classTree.getModifiers().flags & Flags.PRIVATE) != 0;
} else if (tree instanceof JCMethodDecl methodTree) {
return !isSynthesizedConstructor(methodTree) && (methodTree.getModifiers().flags & Flags.PRIVATE) != 0;
return !isConstructor(methodTree) && (methodTree.getModifiers().flags & Flags.PRIVATE) != 0;
} else if (tree instanceof JCVariableDecl variable) {
Symbol owner = variable.sym == null ? null : variable.sym.owner;
if (owner instanceof ClassSymbol) {
return (variable.getModifiers().flags & Flags.PRIVATE) != 0;
return !isSerialVersionConstant(variable) && (variable.getModifiers().flags & Flags.PRIVATE) != 0;
} else if (owner instanceof MethodSymbol) {
return true;
}
Expand All @@ -172,11 +173,9 @@ private boolean isPrivateDeclaration(Tree tree) {
return false;
}

private boolean isSynthesizedConstructor(JCMethodDecl methodDecl) {
boolean isDefaultConstructor = methodDecl.getParameters().isEmpty() && methodDecl.sym != null
private boolean isConstructor(JCMethodDecl methodDecl) {
return methodDecl.sym != null
&& methodDecl.sym.isConstructor();
int endPos = methodDecl.getEndPosition(((JCCompilationUnit) unit).endPositions);
return isDefaultConstructor && endPos < 0;
}

private boolean isPrivateSymbol(Symbol symbol) {
Expand Down Expand Up @@ -207,6 +206,15 @@ private boolean isMemberSymbol(Symbol symbol) {
return false;
}

private boolean isSerialVersionConstant(JCVariableDecl variable) {
long flags = variable.getModifiers().flags;
return (flags & Flags.FINAL) != 0
&& (flags & Flags.STATIC) != 0
&& variable.type instanceof JCPrimitiveType type
&& type.getTag() == TypeTag.LONG
&& "serialVersionUID".equals(variable.name.toString());
}

public List<CategorizedProblem> getUnusedImports(UnusedProblemFactory problemFactory) {
return problemFactory.addUnusedImports(this.unit, this.unusedImports);
}
Expand Down

0 comments on commit 6b671dd

Please sign in to comment.