Android: Load implementations of interface across libraries using Guava(Android:使用Guava加载跨库接口实现)
本文介绍了Android:使用Guava加载跨库接口实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在我的Android应用程序中收集具体接口的所有实现。我有这样的东西:
List<T> list = ClassPath.from(ClassLoader.getSystemClassLoader())
.getTopLevelClasses(Reflection.getPackageName(parent))
.stream()
.map(ClassPath.ClassInfo::load)
.filter(current -> isImplementation(parent, current))
.map(aClass -> (T) aClass)
.collect(Collectors.toList());
但它总是返回0个类。即使我想检索所有类:
ClassPath.from(ClassLoader.getSystemClassLoader())
.getAllClasses()
.stream()
.map(ClassPath.ClassInfo::load)
.collect(Collectors.toList());
总是为零。当我在单元测试中从我的库本地运行它时,它是正常的。可能,这是ClassLoader的问题。它不提供有关应用程序提供的所有包的信息。
我不想使用DexFile,因为它是deprecated 。没有有关entries()替换函数的其他信息。
是否有可能解决此问题?
推荐答案
TLDR:
您可以使用dagger依赖项(或更新,hilt)将组件安装到一个域中,例如SingletonComponent,并通过实现将其作为构造函数参数注入。您甚至可以按设置注入多个实现。
真实答案:
我已经创建库common和test。这些库固定在我的应用程序中。
- 在
common模块中,您可以创建任何界面,如:
public interface Item {
}
- 将依赖项
common设置为test。重新加载依赖项。现在您可以在test库中看到Item。编写实现接口的自定义类:
public class CustomItem implements Item{
//...
}
- 在
test库中创建模块:
@Module
@InstallIn(SingletonComponent.class)
public class TestModule {
@Provides
@Singleton
@IntoSet
public Item customItem() {
return new CustomItem();
}
}
- 在应用程序中设置依赖项
common和test,并使用您的实现集添加模块:
@Module
@InstallIn(SingletonComponent.class)
public class ApplicationSingletonModule {
@Provides
@Singleton
public CustomClassProvider customClassProvider(Set<Item> items) {
return new CustomClassProvider(items);
}
}
您可以添加多个Item实现并将其跨库插入,没有任何问题。
这篇关于Android:使用Guava加载跨库接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:Android:使用Guava加载跨库接口实现
基础教程推荐
猜你喜欢
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
