此语言级别不支持钻石类型

Diamond type are not supported at this language level

将项目导入 Android studio 后,如果我想编译或 运行 项目,它会抛出错误:

Error:(61, 65) java: diamond operator is not supported in -source 1.6
(use -source 7 or higher to enable diamond operator)

有谁知道这是什么以及如何解决?

几天前,我就深受其害。只需更新您的 buildToolsVersion 如下所示。并升级您的 SDK.

    android {
    compileSdkVersion 21
    buildToolsVersion '21.1.2'

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

Diamond operator是Jdk7的新功能之一。请确认您的jdk版本是否为7。这是菱形运算符的示例。

这是一个赋值语句:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

使用菱形运算符:

Map<String, List<String>> anagrams = new HashMap<>();

编辑

将其添加到您的 build.gradle ..

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 21
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

希望对你有用。

借助 Android KitKat(buildToolsVersion 19),您可以使用菱形运算符、多捕获、开关中的字符串、资源尝试等。为此,请将以下内容添加到您的构建文件中:

android {
        compileSdkVersion 19
        buildToolsVersion "19.0.0"

        defaultConfig {
            minSdkVersion 7
            targetSdkVersion 19
        }

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7
        }
    }

请注意,对于除 try with resources 之外的所有语言功能,您可以使用值早于 19 的 minSdkVersion。如果你想尝试使用资源,你还需要使用 19 的 minSdkVersion。

您还需要确保 Gradle 使用的是 JDK 的 1.7 或更高版本。 (以及 Android Gradle 插件的 0.6.1 或更高版本。)

http://tools.android.com/tech-docs/new-build-system/user-guide

在 Android Studio 中(文件 -> 项目结构...,属性选项卡),设置以下值:

Source Compatibility == 1.7
Target Compatibility == 1.7

在此之后,您的 build.gradle 将拥有这些条目:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}

在 Intellij Idea 中,您需要设置项目语言级别(所有模块的默认语言级别)和模块语言级别。

文件 --> 项目结构 --> 项目设置 --> Select 项目 --> 项目语言级别 --> Select 7 - Diamons、ARM、multi-catch 等8 - Lambdas,类型 annoationsetc。选项并单击 应用

在 Intellij 中,至少对我来说,问题是 "Settings->Build, Execution, Deployment->Java Compiler" 下指定的每个模块的目标版本是错误的。

希望这可以节省一些时间。