Move to use reflection to access JDK8 APIs

Currently, KAPT3 uses JDK internal API to build Java AST.
Since the API is internal, it has changed in newer JDKs.
So, for them, use reflection to access new API.
 #KT-59349 Fixed
This commit is contained in:
Donald Duo Zhao
2023-06-29 23:17:04 +00:00
committed by Space Team
parent 56910b70a3
commit a8fcdddf24
3 changed files with 17 additions and 6 deletions
@@ -58,11 +58,11 @@ fun KaptContext.doAnnotationProcessing(
return
}
val initProcessAnnotationsMethod = JavaCompiler::class.java.declaredMethods.single { it.name == "initProcessAnnotations" }
if (isJava9OrLater()) {
val initProcessAnnotationsMethod = JavaCompiler::class.java.declaredMethods.single { it.name == "initProcessAnnotations" }
initProcessAnnotationsMethod.invoke(compiler, wrappedProcessors, emptyList<JavaFileObject>(), emptyList<String>())
} else {
compiler.initProcessAnnotations(wrappedProcessors)
initProcessAnnotationsMethod.invoke(compiler, wrappedProcessors)
}
if (logger.isVerbose) {
@@ -92,7 +92,9 @@ fun KaptContext.doAnnotationProcessing(
processAnnotationsMethod.invoke(compiler, analyzedFiles, additionalClassNames)
compiler
} else {
compiler.processAnnotations(analyzedFiles, additionalClassNames)
val processAnnotationsMethod =
compiler.javaClass.getMethod("processAnnotations", JavacList::class.java, JavacList::class.java)
processAnnotationsMethod.invoke(compiler, analyzedFiles, additionalClassNames) as JavaCompiler
}
} catch (e: AnnotationProcessingError) {
throw KaptBaseError(KaptBaseError.Kind.EXCEPTION, e.cause ?: e)
@@ -263,7 +263,15 @@ private fun JCDiagnostic.Factory.errorJava9Aware(
errorMethod.invoke(this, JCDiagnostic.DiagnosticFlag.MANDATORY, source, pos, key, args) as JCDiagnostic
} else {
this.error(source, pos, key, *args)
val errorMethod = this::class.java.getDeclaredMethod(
"error",
DiagnosticSource::class.java,
JCDiagnostic.DiagnosticPosition::class.java,
String::class.java,
Array<Any>::class.java
)
errorMethod.invoke(this, source, pos, key, args) as JCDiagnostic
}
}
@@ -52,7 +52,8 @@ fun TreeMaker.TopLevelJava9Aware(packageClause: JCTree.JCExpression?, declaratio
val allDeclarations = if (packageDecl != null) JavacList.of(packageDecl) + declarations else declarations
topLevelMethod.invoke(this, allDeclarations) as JCTree.JCCompilationUnit
} else {
TopLevel(JavacList.nil(), packageClause, declarations)
val topLevelMethod = TreeMaker::class.java.declaredMethods.single { it.name == "TopLevel" }
topLevelMethod.invoke(this, JavacList.nil<JCTree.JCAnnotation>(), packageClause, declarations) as JCTree.JCCompilationUnit
}
}
@@ -60,6 +61,6 @@ fun JCTree.JCCompilationUnit.getPackageNameJava9Aware(): JCTree? {
return if (isJava9OrLater()) {
JCTree.JCCompilationUnit::class.java.getDeclaredMethod("getPackageName").invoke(this) as JCTree?
} else {
this.packageName
this.packageName as JCTree?
}
}