前言
在日常的开发当中,我们发现Java8的特性能帮助我们减少部分的代码。那么我们要怎么才能在Android开发当中使用Java8的特性呢?下面分享一下我的方法,希望对Android开发的小伙伴有帮助。
使用Java8特性的方法
在model
里面的build.gradle
文件中android{}
加入下面的代码
android{
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
}
完成上面的配置之后,我们就可以在Android开发的项目里面使用我们的Java8特性了。
可能存在的疑问
我之前有找过很多网上的博客去支持Java8的博客,发现他们博客中有添加多了一个配置,在defaultConfig{}
中添加了下面的代码
defaultConfig {
···
jackOptions {
enabled true
}
}
但是我尝试添加这段代码,但是发现build
的时候没有办法运行,报错显示
Could not find method jackOptions() for arguments [build_7yxxbhkwa2z9nyqnb9ernx71c$_run_closure1$_closure3$_closure9@18b8c9fc] on DefaultConfig_Decorated{name=main, dimension=null, minSdkVersion=DefaultApiVersion{mApiLevel=15, mCodename='null'}, targetSdkVersion=DefaultApiVersion{mApiLevel=28, mCodename='null'}, renderscriptTargetApi=null, renderscriptSupportModeEnabled=null, renderscriptSupportModeBlasEnabled=null, renderscriptNdkModeEnabled=null, versionCode=2, versionName=1.0.1, applicationId=com.xxx.xxxxxxx, testApplicationId=null, testInstrumentationRunner=android.support.test.runner.AndroidJUnitRunner, testInstrumentationRunnerArguments={}, testHandleProfiling=null, testFunctionalTest=null, signingConfig=null, resConfig=[zh], mBuildConfigFields={}, mResValues={}, mProguardFiles=[], mConsumerProguardFiles=[], mManifestPlaceholders={XG_ACCESS_ID=xxxxxxxxxxxx, XG_ACCESS_KEY=xxxxxxxxxxx}, mWearAppUnbundled=null} of type com.android.build.gradle.internal.dsl.DefaultConfig.
解决办法
想要避免出现上面的报错,就把上面defaultConfig{}
去掉就好了。