得到“不支持的类文件版本 52.0"在将模块包含到项目中之后

在 Android Studio 中创建一个空项目并包含一个纯 java 模块后,该模块可以自行编译和完美运行,我在该模块中的每个类上都收到以下错误:

After creating an empty project within Android Studio and including a pure java module, which compiles and works perfectly on its own, I get the following error on every single class within that module:

Error:PARSE ERROR: Error:unsupported class file version 52.0

我尝试使用嵌入式 JDK 和我系统上的 JDK 8 (1.8.0_91) 运行项目,结果是一样的.

I tried to run the project using the embedded JDK and the one that I have on my system - JDK 8 (1.8.0_91), the result is the same.

请注意,我没有将模块包含为 .jar 库,它是使用以下指令导入的源代码:

Note this, that I don't include the module as .jar library, it is source code which is importing with following instruction:

include ':app', ':my-module'
project(':my-module').projectDir = new File(settingsDir, '../my-module-java')

推荐答案

知道了,错误是因为我没有在模块本身中指定兼容性选项.这意味着如果您已安装并使用 JDK 8,并且您的 android 项目使用 Java 1.7(默认情况下在 Android SDK 23 及更低版本中)并且它包含一个没有任何使用 Java 1.7 规范的模块,那么该模块将被编译为JDK 8 使用 Java 1.8 语法并且会出现错误,因为它们不兼容并且使用 Java 1.7 的编译器无法解析针对 Java 1.8 且版本为 52 的类文件.

Got it, the error was because I didn't specify compatibility options in the module itself. That means if you have installed and using JDK 8 and your android project uses Java 1.7 (which is by default in Android SDK 23 and below) and it has a module included without any specification to use Java 1.7, then that module will be compiled with JDK 8 using Java 1.8 syntax and there will be an error because they are not compatible and compiler that uses Java 1.7 can't parse class files which were targeting Java 1.8 and have the version 52.

build.gradle - 此构建文件用于模块级别

apply plugin: 'java'

buildscript {
    tasks.withType(JavaCompile) {
        sourceCompatibility = JavaVersion.VERSION_1_7
        targetCompatibility = JavaVersion.VERSION_1_7
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    // Your libraries here

}

相关文章