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:

public class Upgrade0001 implements IUpgrade {

    protected SDao mSDao;

public class SomeActivity extends Activity {
    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
                         .getMethod("getInstance_", Context.class);

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

No comments:

Post a Comment

If you like this post, please leave a comment :)