Search This Blog

Monday, October 20, 2014

Android Annotations - create @EBean instance from code; Android Annotations inject from code; create instance dynamically

Usually when you need an instance of @EBean you simply use inversion of control:

@EBean
public class Upgrade0001 implements IUpgrade {

    @Bean
    protected SDao mSDao;
}


@EActivity(R.layout.activity_some)
public class SomeActivity extends Activity {
    @Bean
    protected Upgrade0001 mUpgrade0001;
}


but what if you wanted to dynamically create an instance of @EBean from code?

Simple reflection won't help - mSDao will be null:


IUpgrade upgrade = (IUpgrade) Class.forName("Upgrade0001_").newInstance();


Just call the getInstance_ method which every AndroidAnnotations class implements:


Method m = Class
                         .forName(upgradeItem.getUpgradeClassName())
                         .getMethod("getInstance_", Context.class);

Object result = m.invoke(null, this.getApplicationContext());
IUpgrade upgrade = (IUpgrade)result;