我正在尝试使用AndroidAnnotations中的@Bean
注入静态字段:
@EBean
public class LogUtil {
@Bean(CrashReporting.class) static Reporting reporting;
public static void log(Activity activity, String method) {
reporting.log(activity.getClass().getName() + ":" + method);
}
}
...
@EBean(scope = EBean.Scope.Singleton)
public class CrashReporting implements Reporting {
@Override
public void log(String text) {
Log.d(getClass().getName(), text);
}
}
reporting
字段在运行时为空:
Caused by: java.lang.NullPointerException:
Attempt to invoke interface method
'void com.example.staticinjection.Reporting.log(java.lang.String)'
on a null object reference
at com.example.staticinjection.LogUtil.log(LogUtil.java:15)
at com.example.staticinjection.MainActivity.onCreate(MainActivity.java:12)
at android.app.Activity.performCreate(Activity.java:6237)
...
答案 0 :(得分:0)
注入的字段仅在调用@AfterInject
带注释的方法后才可用。你是否在那之后访问了该领域?
编辑:你不能真正使用静电注入。您必须将bean注入Activity的实例成员:
@EActivity
public class MainActivity extends AppCompatActivity {
@Bean
LogUtil logger;
@AfterInject
public void afterInject() {
logger.log(this, "AFTERINJECT");
}
}
@EBean
public class LogUtil {
@Bean(CrashReporting.class) Reporting reporting;
public void log(Activity activity, String method) {
reporting.log(activity.getClass().getName() + ":" + method);
}
}