I would like to inject my context to my Utility classes, I have seen examples using 开发者_如何学运维Static fields, Are there any ways to do it with out static fields?
I tend to use a Provider to inject the context when I need it.
public class MyClass
{
private Provider<Context> contextProvider;
@Inject
public MyClass(Provider<Context> contextProvider)
{
this.contextProvider = contextProvider;
}
public doSomething()
{
Context c = contextProvider.get();
}
}
You can do this in several ways, Pass the context to Utility class or use a service locator or anotate the utility class with @Inject
attribute. See more details here.
精彩评论