aleludovici
aleludovici

Reputation: 81

Reflect annotations from android activity class

I am developing an API to be used in Android. I want to use reflection to access annotations that are implemented in the android activity class. I need to reflect it from my API. There is a way to do it?

I am trying to pass the context to the API but I can get the activity class where the annotations are.

The annotation is called action and is as follows:

@Action(
    name = "test",
    description = "this is just a test",
    inputs = {"no input"},
    output = {"no output"},
    controlURL = "/api/v1/"
) public void testAction (){
    /*
     * Implements here the Action!
     */
}

The method I used to reflect it:

private static void getAction() {
    if (D) Log.d(TAG, "getAction"); 

    Class classWithAction = AppContext.getClass();

    Annotation[] aAnnotations = classWithAction.getDeclaredAnnotations();
    for(Annotation a : aAnnotations)
        Log.d(TAG, a.toString());
 }

Upvotes: 0

Views: 679

Answers (1)

Marcin Łoś
Marcin Łoś

Reputation: 3246

Discovering all classes annotated with particular annotation in runtime requires, in general, classpath scanning. There is no streamlined, official API for doing it, though. This is because it is, always and inevitably, a hack, due to design of classloading system. In short, classes can, in principle, be created on demand, in completely uncontrollable and arbitrary manner.

Nevertheless, usually the classpath jungle is by no means that vicious and frought with pitfalls, and we can list all the classes with particular property reasonably reliably. There is one android-specific obstacle to overcome, but it's not too bad. Basically, the trick is to list contents of classes.dex file in the app's .apk archive, load classes it contains one by one and reflectively check for the desired property. You can get more details here (my other answer), and this blog post contains fairly complete illustration of this technique (it's not mine).

Upvotes: 1

Related Questions