Browse Source

Refine SourceFile record to class conversion

Update conversion logic to deal with annotations.

See gh-29236
pull/29242/head
Phillip Webb 2 years ago
parent
commit
afac8dd8af
  1. 27
      spring-core-test/src/main/java/org/springframework/core/test/tools/SourceFile.java
  2. 13
      spring-core-test/src/test/java/org/springframework/core/test/tools/SourceFileTests.java

27
spring-core-test/src/main/java/org/springframework/core/test/tools/SourceFile.java

@ -22,6 +22,8 @@ import java.io.IOException; @@ -22,6 +22,8 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaClass;
@ -189,7 +191,30 @@ public final class SourceFile extends DynamicFile implements AssertProvider<Sour @@ -189,7 +191,30 @@ public final class SourceFile extends DynamicFile implements AssertProvider<Sour
}
private static String makeRecordsLookLikeClasses(String content) {
return content.replaceAll("record\\s(\\S+)\\(\\X+?\\)", "class $1");
Pattern pattern = Pattern.compile("record\\s(\\S+)\\(");
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
StringBuilder result = new StringBuilder();
result.append(content.substring(0, matcher.start()) + "class");
result.append(content.substring(matcher.start() + 6, matcher.end() - 1));
int parenthesesCount = 1;
for (int i = matcher.end(); i < content.length(); i++) {
char ch = content.charAt(i);
if (parenthesesCount > 0) {
if (ch == '(') {
parenthesesCount++;
}
else if (ch == ')') {
parenthesesCount--;
}
}
else {
result.append(ch);
}
}
return makeRecordsLookLikeClasses(result.toString());
}
return content;
}
/**

13
spring-core-test/src/test/java/org/springframework/core/test/tools/SourceFileTests.java

@ -146,6 +146,19 @@ class SourceFileTests { @@ -146,6 +146,19 @@ class SourceFileTests {
assertThat(sourceFile.getClassName()).isEqualTo("com.example.helloworld.HelloWorld");
}
@Test
void getClassNameFromAnnotatedRecord() {
SourceFile sourceFile = SourceFile.of("""
package com.example;
public record RecordProperties(
@org.springframework.boot.context.properties.bind.DefaultValue("default-value-1") String property1,
@org.springframework.boot.context.properties.bind.DefaultValue("default-value-2") String property2) {
}
""");
assertThat(sourceFile.getClassName()).isEqualTo("com.example.RecordProperties");
}
/**
* JavaPoet style API with a {@code writeTo} method.
*/

Loading…
Cancel
Save