【问题标题】:RoboGuice: inject class by hand in normal classRoboGuice:在普通类中手动注入类
【发布时间】:2014-09-08 16:37:59
【问题描述】:

我有一些接口,一些具体的类实现了这些接口。我在AbstractModule 类中有配置。

但我的问题是:@Inject 只能在 RoboGuice 类中工作,例如 RoboFragment、RoboActivity ...

例如:

public class Fragment extends RoboFragment {

  @Inject
  ICustomClass helper; // work. helper will be initialized and call successfully. 

}

public class JavaNormalClass {
  @Inject
  ICustomClass helper;  // doesn't work. NullPointerException
}

所以,我认为RoboGuice 在普通类中时不会注入自定义类,所以我应该手动调用它。 (我猜!!!)那么,如何解决我的问题?

谢谢:)

【问题讨论】:

    标签: java android dependency-injection roboguice


    【解决方案1】:

    这个简单的解决方案对我有用。

    您在调用任何@Inject 成员之前放置了这行代码。最好的方法可能是普通类的构造函数或活动的onCreate ...

    public class CustomClass {
    
       @Inject
       IDBDAL dbDAL;
    
       // can be application context or activity context
       private Context mContext;
    
       public CustomClass() {
          // you can get context variable somewhere else 
          mContext = MyApplication.getAppContext(); 
          RoboGuice.getInjector(mContext).injectMembersWithoutViews(this);
          // from now. you can use dbDAL object
          dbDAL.doSomething(); // work like charm :)
       }
    }
    

    我认为这个解决方案是通用的,可以适用于多种情况。希望对您有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 2019-02-16
      相关资源
      最近更新 更多