简体   繁体   English

注入超型匕首2

[英]Injecting into supertype dagger2

Is it possible to inject into supertypes in Dagger 2? 是否可以在Dagger 2中注入超类型?

if I have a property like this 如果我有这样的财产

@Inject
Wallet<Material>

Would the following provide work ? 以下内容可以提供工作吗?

@Provides
Wallet<LeatherMaterial> provide()
{
return new Wallet<LeatherMaterial>
}

Actually I should have rephrased the question . 其实我应该改掉这个问题。 It isn't working and I get an error that demands an injection of the exact Wallet 它无法正常工作,并且出现错误,需要注入确切的电子钱包

do we have any workarounds ? 我们有什么解决方法吗? . does koin provide some functionality like this? koin是否提供这样的功能?

Yes, you need to be explicit. 是的,您需要明确。 Add the following to your Module, if you already have Wallet<LeatherMaterial> in your dependency graph somewhere: 如果您的依赖图中某处已经有Wallet<LeatherMaterial> ,请在模块中添加以下内容:

@Binds abstract Wallet<Material> provide(Wallet<LeatherMaterial> leatherWaller);

Otherwise, go with: 否则,请继续:

@Provides static Wallet<Material> provide() {
    return new Wallet<LeatherMaterial>(){ /* ... */ };
}

Edit: Revisiting this answer because it occured to me the solutions I've provided wont work due to how generics are treated in Java. 编辑:重新回答这个问题,因为在我看来,由于Java中如何处理泛型,我提供的解决方案无法正常工作。 Instead, you would need to use: 相反,您将需要使用:

Wallet<? extends Material> Wallet<? extends Material> in place of Wallet<Material> in my above answers, and do the same wherever it is injected as well. 在我上面的答案中, Wallet<? extends Material>代替Wallet<Material>进行了Wallet<? extends Material> ,并且无论注入到哪里,都执行相同操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM