Android Studio Arctic Fox下如何让framework.jar优先android.jar编译适配JVM1.8+
适配JVM 1.8及以上版本的framework.jar优先编译解决方案
一、Gradle脚本修改(适配全JVM版本+编译优先级调整)
原来的代码仅处理了Java编译的引导类路径,未覆盖高版本JDK的模块化限制、Kotlin编译、AGP 7+的新规则,修改后的完整配置如下:
步骤1:模块级build.gradle配置
在app或者对应模块的build.gradle文件中添加以下方法并调用:
def addFrameworkJarToCompile(Project project) { File frameworkFile = new File(rootDir, "../libs/framework.jar") if (!frameworkFile.exists()) { throw new GradleException("framework.jar不存在,路径:${frameworkFile.absolutePath}") } // 处理Java编译引导类路径,兼容JDK1.8及以上版本 project.android.compileOptions { if (bootstrapClasspath != null) { def originalBootFiles = bootstrapClasspath.files bootstrapClasspath = project.files(frameworkFile, *originalBootFiles) } sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 // JDK9+ 模块化参数配置,避免高版本JDK编译权限报错 options.forkOptions.jvmArgs += [ "--add-opens", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", "--add-opens", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED" ] } // 适配Kotlin编译类路径(项目使用Kotlin时生效) project.plugins.withId('kotlin-android') { project.kotlinOptions { jvmTarget = "1.8" freeCompilerArgs += ["-Xbootclasspath/a:${frameworkFile.absolutePath}"] } } // 适配AGP7+ Lint检查类路径,避免隐藏API检查报错 project.android.lintOptions { classpath = project.files(frameworkFile, classpath) } } // 调用方法生效 addFrameworkJarToCompile(project) android { // 原有android闭包配置保持不变 namespace "com.xxx.xxx" compileSdk 30 // ...其余原有配置 } dependencies { // 新增compileOnly引入framework.jar,不会打包到APK compileOnly files('../libs/framework.jar') // ...其余原有依赖配置 }
步骤2:项目根级build.gradle配置
在根目录build.gradle的allprojects闭包中添加自动调整类路径优先级的配置,避免每次同步后手动修改iml文件:
// 根级build.gradle开头先定义全局framework.jar路径 ext.frameworkFile = new File(rootDir, "libs/framework.jar") // 路径和你实际存放位置保持一致 allprojects { repositories { google() mavenCentral() } // 自动调整编译类路径优先级 gradle.projectsEvaluated { tasks.withType(JavaCompile) { options.compilerArgs.add("-Xbootclasspath/p:${frameworkFile.absolutePath}") } } afterEvaluate { project -> if (project.plugins.hasPlugin("com.android.application") || project.plugins.hasPlugin("com.android.library")) { project.android.libraryVariants.all { variant -> def javaCompile = variant.javaCompileProvider.get() javaCompile.classpath = project.files(frameworkFile) + javaCompile.classpath } } } }
二、编辑器标红问题修复
完成上述gradle配置后执行以下操作即可:
- 点击Android Studio顶部菜单
File -> Sync Project with Gradle Files同步gradle配置 - 同步完成后点击
File -> Invalidate Caches...,选择Invalidate and Restart重启Android Studio - 重启后编辑器会优先从framework.jar读取类、方法、字段定义,标红问题即可解决
内容的提问来源于stack exchange,提问作者Fang
相关产品推荐
相关产品推荐

