我有一个 Car
扩展类 Vehicle
类,我将在车辆类中注入(inject)一些属性。
示例 已编辑
abstract class Vehicle {
@Inject
lateinit var default: Default
}
class Car @Inject constructor(): Vehicle() {
}
在我的代码中一切正常,But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?
is this the proper way of injecting?
谁能澄清这一点?
最佳答案
But one thing i need to know is that how the dagger injects the properties in base class or its hierarchy?
为此,您可以查看生成的源文件。在你的情况下会有这样的事情:
class Car_Factory implements Factory<Car> {
@Override
public Car get() {
return provideInstance(
defaultProvider
);
}
public static Car provideInstance(
Provider<Default> defaultProvider
) {
Car instance = new Car();
Vehicle_MembersInjector.injectDefault(instance, defaultProvider.get()); // just instance.default = default here
return instance;
}
}
如您所见,它将创建您的实例,然后将访问它的字段(只要它们是公共(public)的和可写的)。
is this the proper way of injecting?
不推荐这种方式,因为您公开了可能是私有(private)(或 protected )的字段,并且您允许外部其他人进行修改,这违反了封装。
因此最好以这种方式使用构造函数注入(inject):
abstract class Vehicle(protected val default: Default)
class Car @Inject constructor(default: Default) : Vehicle(default)
这样,Dagger 将使用已经初始化的字段创建您的实例,并且不会访问它们
关于android - 基类中的 Dagger 注入(inject)是一种好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62172108/