From b5a60b2e78bbf7ae5f9957ebe6cbb6a6272a5d68 Mon Sep 17 00:00:00 2001 From: Jordan Zimmerman Date: Wed, 27 Mar 2024 17:31:29 +0000 Subject: [PATCH] Delete existing class files to avoid JDK/IntelliJ bugs https://github.com/Randgalt/record-builder/pull/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 --- .../processor/RecordBuilderProcessor.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/record-builder-processor/src/main/java/io/soabase/recordbuilder/processor/RecordBuilderProcessor.java b/record-builder-processor/src/main/java/io/soabase/recordbuilder/processor/RecordBuilderProcessor.java index 643d8e5c..b76e30fa 100644 --- a/record-builder-processor/src/main/java/io/soabase/recordbuilder/processor/RecordBuilderProcessor.java +++ b/record-builder-processor/src/main/java/io/soabase/recordbuilder/processor/RecordBuilderProcessor.java @@ -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; @@ -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); @@ -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); @@ -263,4 +268,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 + } + } }