Android Billing4.0升级5.0时ImmutableList.of方法无法解析如何解决
问题说明
- 操作场景:将Android Billing库从4.0版本迁移至5.0版本,编写「展示可购买商品」章节对应代码时,Android Studio将
ImmutableList的of方法标红,抛出如下编译错误:
Cannot resolve method 'of' in 'ImmutableList'
- 可复现错误的最小代码片段:
QueryProductDetailsParams queryProductDetailsParams = QueryProductDetailsParams.newBuilder() .setProductList( ImmutableList.of( QueryProductDetailsParams.Product.newBuilder() .setProductId(PREMIUM_MONTHLY_VERSION_ID) .setProductType(BillingClient.ProductType.SUBS) .build())) .build();
- 预期结果:代码可正常编译通过
- 当前异常:出现上述编译错误,无法完成编译
解决方案
这个错误是ImmutableList类导入错误或依赖缺失导致的,可按以下优先级排查解决:
- 检查导包语句
首先确认文件顶部导入的ImmutableList是Guava库的类,导包语句应为:
如果误导入Java 9+内置的import com.google.common.collect.ImmutableList;java.util.ImmutableCollections、或其他第三方库的同名ImmutableList类,就会出现找不到of方法的错误,替换导包语句即可解决。 - 补全Guava依赖
Android Billing 5.0及以上版本不会自动向业务层传递可用的Guava依赖,如果项目中没有引入Guava、或引入的Guava版本过低(低于31.0-android),也会触发该错误。
在模块级Gradle配置文件的dependencies块中添加Guava依赖后同步项目即可:dependencies { // 其余已有依赖 implementation 'com.google.guava:guava:33.0.0-android' } - 无Guava依赖的替代写法
如果不想额外引入Guava库,可以直接使用Java标准库的集合类构造参数传入,setProductList方法仅要求参数为List<Product>类型,不强制使用不可变集合:- 单个商品场景直接用
Collections.singletonList():
QueryProductDetailsParams queryProductDetailsParams = QueryProductDetailsParams.newBuilder() .setProductList( Collections.singletonList( QueryProductDetailsParams.Product.newBuilder() .setProductId(PREMIUM_MONTHLY_VERSION_ID) .setProductType(BillingClient.ProductType.SUBS) .build())) .build();- 多个商品场景用
Arrays.asList()传入所有商品实例即可,无需额外依赖。
- 单个商品场景直接用
内容的提问来源于stack exchange,提问作者TomV
相关产品推荐
相关产品推荐

