Advanced setup - rgeldmacher/leash GitHub Wiki

Avoiding Reflection calls

Leash is a compile-time annotation processor that generates code to avoid using Reflection at runtime. However for convenience sake the static wrapper class Leash uses reflection to call the static methods of the generated code. This happens only once for each call to Leash, which makes two calls for each orientation change in most scenarios. This seemed acceptable to me, but why does Leash use Reflection at all?

One of the problems with using source code that is generated at compile time is that it requires one compile run before the IDE can pick it up. So especially when using Leash for the first time the IDE will report errors for the use of the generated classes and developers may be put off. Using the static Leash class hides the generated code from the developer (although it is still debuggable) and makes using the API much easier. However developers that want to avoid Reflection at all costs, can still do that and directly call the generated classes.

The annotation will generate code at compile time and create the class <YourActivity>Leash. You can directly call restore()and retain() on these classes and bypass the Leash class to avoid reflection:

public class ExampleActivity extends Activity {

    @Retain
    List<Foo> data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExampleActivityLeash.restore(this);
        // use your retained data ...
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        ExampleActivityLeash.retain(this);
    }

You will experience some inconvenience while editing in the IDE, but fortunately with android-apt plugin there is a great plugin to reduce some of the problems. See Android Studio Integration.

Android Studio Integration

While the annotation itself will work out of the box, Android Studio does not automatically pick up the generated code and thus cannot provide auto-completion on the generated classes and will mark their usages as error. To fix this you can add the android-apt plugin by Hugo Visser to your setup and Android Studio will pick up the generated code.

Add android-apt to your build scripts:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    }
}

And apply to your module:

apply plugin: 'com.neenbedankt.android-apt'
⚠️ **GitHub.com Fallback** ⚠️