Skip to content

Commit

Permalink
Delete existing class files to avoid JDK/IntelliJ bugs
Browse files Browse the repository at this point in the history
#147 attempted
to do this but it only did it for Record Interface classes.
This commit does it for all classes that are to be generated.
Ad hoc testing shows that it solves the problem.

Fixes #139
  • Loading branch information
Randgalt committed Mar 27, 2024
1 parent 71353e0 commit 959b1e7
Showing 1 changed file with 23 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.Optional;
Expand Down Expand Up @@ -218,6 +221,7 @@ private void writeRecordBuilderJavaFile(TypeElement record, String packageName,
try {
String fullyQualifiedName = packageName.isEmpty() ? builderClassType.name()
: (packageName + "." + builderClassType.name());
deletePossibleClassFile(packageName, builderClassType.name());
JavaFileObject sourceFile = filer.createSourceFile(fullyQualifiedName);
try (Writer writer = sourceFile.openWriter()) {
javaFile.writeTo(writer);
Expand All @@ -235,6 +239,7 @@ private void writeRecordInterfaceJavaFile(TypeElement element, String packageNam

Filer filer = processingEnv.getFiler();
try {
deletePossibleClassFile(packageName, classType.name());
String fullyQualifiedName = packageName.isEmpty() ? classType.name()
: (packageName + "." + classType.name());
JavaFileObject sourceFile = filer.createSourceFile(fullyQualifiedName);
Expand Down Expand Up @@ -263,4 +268,22 @@ private void handleWriteError(TypeElement element, IOException e) {
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
}

private void deletePossibleClassFile(String packageName, String className) {
try {
className += ".class";

FileObject resource = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, packageName,
className);
File file = new File(resource.toUri());
if (file.exists()) {
if (!file.delete()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.MANDATORY_WARNING,
"Could not delete existing class file: %s".formatted(file));
}
}
} catch (IOException e) {
// ignore
}
}
}

0 comments on commit 959b1e7

Please sign in to comment.