“Reflection bridge” approach

This approach is quite sophisticated and when I first saw it and analysed it, I must say I was super impressed...

From the perspective of “noob-proofing”, this is the opposite approach from the previous one. It takes the full responsibility on the proper operation on the library itself.

The core of this approach is the third component, the Library:

This is something that, by design, has to be able to work in runtime, so it needs to be included in your application.

Since both Library & Annotations should (usually) be included in your app, they can be merged together:

The most important thing about the approach is that the library has some knowledge about the way compiler generates code:

It knows what is the policy of naming the generated code. It knows what will be the exposed api of the generated code. The most elegant way to accomplish that is for the library to “share” an interface with the compiler (that will be implemented by the generated code).

Those are the two essential features of something I like to call a Reflection Bridge.

It is a library component that with some help from Java Reflection can:

Find the generated code (using the knowledge about the code naming) Execute the generated code (using the knowledge about the code api)

All this happens in runtime.

The best example of this approach is Jake Wharton’s Butterknife library:

The Butterknife library knows that classes generated by the compiler will:

When you add any of the Butterknife’s @Bind annotations to your class (let’s take for example MainActivity ), Butterknife’s compiler will detect that and generate for it the MainActivity_ViewBinding class:

The most important part of the Butterknife’s library is the Butterknife class itself. When you call:

(continuing the MainActivity example)

The library will use its Reflection Bridge to:

Find the MainActivity_ViewBinding class. Create an instance of MainActivity_ViewBinding class. Let you have it in the form of Unbinder interface.

This way, in a clean and elegant way (I know some people say Reflection is not elegant, but I believe this is an acceptable usage of it), the library will communicate with the generated code during runtime.