Static provide method in Dagger2

无人久伴 提交于 2019-12-10 18:33:45

问题


Why should use static modifier before the provide method?

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

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

回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/38607503/static-provide-method-in-dagger2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!