3

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?

iraSenthil
  • 11,307
  • 6
  • 39
  • 49

2 Answers2

7

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();
    }
}
el-milligano
  • 2,146
  • 1
  • 13
  • 6
1

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.

iraSenthil
  • 11,307
  • 6
  • 39
  • 49
  • 2
    FYI, the linked article references the RoboGuice 1 way of doing things, not the newer RoboGuice 2+ way. – Jon Adams Mar 26 '13 at 15:08