From b72ec9a3679731150f41488431353a8f8d027794 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 | 23 +++++++++++++++++++ 1 file changed, 23 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..8591a064 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; @@ -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); @@ -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); @@ -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 + } + } }