Dagger2中的静态提供方法 [英] Static provide method in Dagger2

查看:83
本文介绍了Dagger2中的静态提供方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要在提供方法之前使用静态修饰符?

Why should use static modifier before the provide method?

即使我删除了静态修饰符,dagger2也可以正常工作。

Even though I remove the static modifier, dagger2 works correctly.

@Provides static Pump providePump(Thermosiphon pump) {
    return pump;
}


推荐答案

两种样式均可;是否将方法保持静态完全取决于您,在普通的旧Java中,通常的判断是应该是静态方法。在这里, pump 对于模块实例没有任何用处,因此该方法可以轻松地实现静态。

Both styles work; whether you keep the method static is entirely up to you and your normal "should this be a static method" judgment in plain old Java. Here, pump doesn't have any use for a module instance, so the method can easily be static.

静态方法调用更快,尤其是在Android 中,因为它们避免了虚拟方法表查找。这也可能使它们更易于编译器,JIT运行时或静态分析工具内联。我想您会通过使类或方法 final 来打开类似的优势。

Static method calls are faster, particularly in Android, because they avoid a virtual method table lookup. This may also make them easier for compilers, JIT runtimes, or static analysis tools to inline. I'd surmise you'd open up similar advantages by making the class or method final.

鉴于静态方法不受实例字段约束,因此可读性略有提高。但这取决于您。

There may also be a slight improvement in readability given that a static method can't be subject to instance fields, but that's up to you.

如果您确信@Provides方法的行为在测试中不会发生变化,那么您可以利用性能/可读性的提高。但是,如果您需要引用模块状态或希望允许子类/测试覆盖,则实例方法必然是正确的调用。

If you are confident that your @Provides method's behavior is not subject to change including in tests, then you can take advantage of the performance/readability increase. However, if you need to refer to module state or want to allow subclass/testing overrides, then an instance method is necessarily the right call.

这篇关于Dagger2中的静态提供方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆