Search code examples
javaannotationsprocessor

Annotation processing for pubsub


I have 3rd party library that uses kafka to abstract pub sub mechanism. I have something like following to subscribe topic

DDS.createListener((topic) -> "do sth with this topic");

I want to take it further and want to create an annotation as follows

@Subscribe("topicName")
public void listen(Topic topic) {
    // do sth with this topic
}

I am having problems when processing annotation.

First, I need to find methods annotated with Subscribe and then need to listen for topics behind the curtain and then when one received, direct it to the annotated method, "listen" in the example case. Where should I do the listen part which is

DDS.createListener((topic) -> listen() /* dunno how to access listen */)

And also to invoce the listen method, I need a class instance but I am not sure how I am gonna handle that. It does not make sense to do Class.newInstance(). Do I need a different kind of configuration?


Solution

  • You need to create register(Object obj) method in a wrapper class which handles your topic registration. This needs to be called in constructor of class where you have subscribe method.

    so whenever some one calls register(this) method you will get object reference and you need to find @Subscribe annotated method and create listener which will call given method using reflection.

    There other ways but this seems to be easiest