0

I'm trying to learn annotation processors. I'm trying to create a custom annotation that would send a certain object to a certain method. Both of them will be annotated with the same annotation.

For Example:

public void processData(@MyAnnotation("xyz") Object obj) {
     // applies certain computations on the obj and then broadcasts the object using Android's Broadcast
}

Now there are 2 methods that have one argument of type Object. I want my annotaton processor to intercept the Android Broadcast & then call the method that's @MyAnnotation("xyz") annotation only.

@MyAnnotation("xyz")
public void method1(Object obj) {//...
}

@MyAnnotation("abc")
public void method2(Object obj) {//...
}

So in this case, the custom annotation processor will call ONLY method 1.

I'm not really sure if this is even possible, but if it's, How can I acheive this? I don't want code. I want direction and may be a tutorial that can help me achieve this custom annotation on my own.

user2498079
  • 2,872
  • 8
  • 32
  • 60
  • I don't think that is possible. Annotation processors can't modify the abstract syntax tree directly, only generate new class files. (Technically it *is* possible, but it's very difficult and involves unsupported, undocumented Javac API.) There's a good intro to code generation with annotation processing (in the supported way) [here](https://deors.wordpress.com/2011/09/26/annotation-types/) if you want to learn it. – Radiodef Apr 22 '17 at 22:53
  • @Radiodef Dagger2 does something similar. is my requirement different then the one implemented by dagger 2? – user2498079 Apr 23 '17 at 07:17
  • If everything you want to do ends up in a new class file (like in the case of a factory), then it's possible. It could be that I misunderstood what you're asking for. The link I gave in my previous comment explains how to generate new class files. (Instead of creating a `String` source file in the annotation processor, there are also APIs like JavaPoet.) I don't really know much about Dagger2, but since it's DI I don't think it would need to modify the AST. Also, there are annotation processors that use the Javac API I mentioned, like Lombok. – Radiodef Apr 23 '17 at 14:38

0 Answers0