编译错误解决
报错信息
jetified-objenesis-3.0.1.jar: D8: com.android.tools.r8.internal.n1: MethodHandle.invoke and MethodHandle.invokeExact are only supported starting with Android O (--min-api 26)
Failed to transform objenesis-3.0.1.jar (org.objenesis:objenesis:3.0.1) to match attributes {artifactType=android-dex, asm-transformed-variant=NONE, dexing-enable-desugaring=true, dexing-is-debuggable=true, dexing-min-sdk=23, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
> Execution failed for DexingWithClasspathTransform: 6edd45f2900e2313d0b955213ddd0e2c\transformed\jetified-objenesis-3.0.1.jar.
> Error while dexing.
原因及解决方案
原因
在项目中引入了 mockito,powermock 等测试库,如下:
// Optional -- Mockito framework
implementation 'org.mockito:mockito-core:3.3.3'
// https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2
implementation group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.9'
implementation group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.9'
而 mockito-core 依赖了 org.objenesis:objenesis
(通过 https://search.maven.org/artifact/org.mockito/mockito-core/4.5.1/jar 进行确认) ,Objenesis 是一个用于绕过构造器创建对象的库,其中使用到了 MethodHandle.invokeExact
方法,而android是在26才引入了 MethodHandle 类的(可参考 android官方文档-java/lang/invoke/MethodHandle ,其上有注明: Added in API level 26MethodHandle
。
关于Objenesis 的介绍可参考: https://blog.csdn.net/top_code/article/details/52964854
解决
因为我们这个模块之所以引入mockito-core 是为了提供给测试模块一些基本封装的功能,而实际上被测试模块会通过 androidTestimplementation 来引入mockito及powermock的依赖,且编译及运行测试模块不会有问题。所以我们只需要把这个基础库模块依赖方式 implementation
替换为 compileOnly
即可:
// Optional -- Mockito framework
compileOnly 'org.mockito:mockito-core:3.3.3'
// https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2
compileOnly group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.9'
compileOnly group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.9'