Skip to content

Commit

Permalink
Fix adding private/static/final modifiers to interface fields
Browse files Browse the repository at this point in the history
  • Loading branch information
sambsnyd committed Sep 27, 2024
1 parent 5c43d94 commit 07e416e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Objects.requireNonNull;
import static org.openrewrite.Tree.randomId;

@Value
Expand Down Expand Up @@ -71,7 +72,7 @@ public Duration getEstimatedEffortPerOccurrence() {
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new UsesType<>("java.lang.String", false), new JavaVisitor<ExecutionContext>() {
@Override
public J visit(@Nullable Tree tree, ExecutionContext ctx) {
public @Nullable J visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof JavaSourceFile) {
JavaSourceFile cu = (JavaSourceFile) tree;
Optional<JavaSourceSet> sourceSet = cu.getMarkers().findFirst(JavaSourceSet.class);
Expand Down Expand Up @@ -117,7 +118,8 @@ public J visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ct
continue;
}
J.Literal replaceLiteral = duplicateLiterals.get(0).withId(randomId());
JavaTemplate template = JavaTemplate.builder("private static final String " + variableName + " = #{any(String)};").build();
String modifiers = (classDecl.getKind() == J.ClassDeclaration.Kind.Type.Interface) ? "" : "private static final ";
JavaTemplate template = JavaTemplate.builder(modifiers + "String " + variableName + " = #{any(String)};").build();
if (classDecl.getKind() == J.ClassDeclaration.Kind.Type.Enum) {
J.Block applied = template
.apply(new Cursor(getCursor(), classDecl.getBody()), classDecl.getBody().getCoordinates().lastStatement(), replaceLiteral);
Expand All @@ -136,7 +138,7 @@ public J visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ct
duplicateLiteralInfo = null;
duplicateLiteralsMap = null;
return replacements.isEmpty() ? classDecl :
new ReplaceStringLiterals(classDecl, replacements).visitNonNull(classDecl, ctx, getCursor().getParent());
new ReplaceStringLiterals(classDecl, replacements).visitNonNull(classDecl, ctx, requireNonNull(getCursor().getParent()));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -577,4 +577,28 @@ enum Scratch {
)
);
}

@Test
void interfaceLiteralsCannotBePrivate() {
rewriteRun(
//language=java
java(
"""
interface A {
String val1 = "value";
String val2 = "value";
String val3 = "value";
}
""",
"""
interface A {
String VALUE = "value";
String val1 = VALUE;
String val2 = VALUE;
String val3 = VALUE;
}
"""
)
);
}
}

0 comments on commit 07e416e

Please sign in to comment.