Android潜修者

AndroidStudio对于Java8特性的支持

2017-02-20  本文已影响12818人  nianyounan

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.
上一篇下一篇

猜你喜欢

热点阅读