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 b72ec9a
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 @@ -216,6 +219,8 @@ private void writeRecordBuilderJavaFile(TypeElement record, String packageName,
JavaFile javaFile = javaFileBuilder(packageName, builderType, metaData);
Filer filer = processingEnv.getFiler();
try {
deletePossibleClassFile(packageName, builderClassType.name());

String fullyQualifiedName = packageName.isEmpty() ? builderClassType.name()
: (packageName + "." + builderClassType.name());
JavaFileObject sourceFile = filer.createSourceFile(fullyQualifiedName);
Expand All @@ -235,6 +240,8 @@ 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 +270,20 @@ private void handleWriteError(TypeElement element, IOException e) {
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
}

private void deletePossibleClassFile(String packageName, String className) {
try {
FileObject resource = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, packageName,
className + ".class");
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 b72ec9a

Please sign in to comment.