AndroidStudio對于Java8特性的支持

AndroidStudio從2.1開始官方通過Jack支持Java8,從而使用Lambda等特性。

配置也很簡單:

android {
  ...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  ...
}```

如果沒有打開jackOptions的配置,那么會提示如下錯誤:

Error:Jack is required to support java 8 language features. Either enable Jack or remove sourceCompatibility JavaVersion.VERSION_1_8.


但是如果打開jackOptions,意味著ButterKnife,Dagger等基于APT的注解框架將無法使用。會提示如下錯誤:

Error:Could not find property ‘options’ on task ‘:app:compileDebugJavaWithJack’.


##解決方法:

使用第三方的Java8兼容插件,[retrolambda](https://github.com/evant/gradle-retrolambda)。
在project的根build.gradle里添加:

dependencies {
classpath'me.tatarka:gradle-retrolambda:3.2.5'
}

然后在module的build.gradle里添加:
`apply plugin:'me.tatarka.retrolambda' `

當然下面compileOptions是少不了的:

android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}


###如果你還不了解Jack & Jill
那么現在你已經不用了解了!
[Google 又棄坑了,Jack+Jill vs. javac+dx](https://zhuanlan.zhihu.com/p/25814519)

官方post:
[Future of Java 8 Language Feature Support on Android - 科學上網](https://android-developers.googleblog.com/2017/03/future-of-java-8-language-feature.html)

原文:
> 
At Google, we always try to do the right thing. Sometimes this means adjusting our plans. We know how much our Android developer community cares about good support for Java 8 language features, and we're changing the way we support them. 
>
We've decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack toolchain. With this new direction, existing tools and plugins dependent on the Java class file format should continue to work. Moving forward, Java 8 language features will be natively supported by the Android build system. We're aiming to launch this as part of Android Studio in the coming weeks, and we wanted to share this decision early with you. 
>
We initially tested adding Java 8 support via the Jack toolchain. Over time, we realized the cost of switching to Jack was too high for our community when we considered the annotation processors, bytecode analyzers and rewriters impacted. Thank you for trying the Jack toolchain and giving us great feedback. You can continue using Jack to build your Java 8 code until we release the new support. Migrating from Jack should require little or no work. 
>
We hope the new plan will pave a smooth path for everybody to take advantage of Java 8 language features on Android. We'll share more details when we release the new support in Android Studio.
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容