I was wondering how I might make an annotation processor that would flag uses of a class's constructor without a subsequent call to a particular method. This related to a previous question of "finding a previously annotated method", but I need to analyze expressions that reference a class, not just method invocations.
Say I have an Interface RegistersListeners:
public interface RegistersListeners {
public void registerListeners();
}
... an annotation RequiresListerners:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface RequiresListerners {
public boolean enabled() default true;
}
... and an annotated class Musician:
@RequiresListerners
public class Musician implements RegistersListeners {
private final AudienceListener audience;
private final ProListener professional;
public Musician(AudienceListener audience, ProListener professional) {
this.audience = audience;
this.professional = professional;
}
@Override
public void registerListeners() {
this.audience.listenTo(this);
this.professional.listenTo(this);
}
}
Next, I use the Musician class from within a Venue class:
class Venue {
Venue() {
AudienceListener smoe = new AudienceListener();
ProListener pro = new ProListener();
/***
* Processor should complain here that this constructor returns
* without calling registerListeners()
***/
Musician johnny = new Musician(smoe,pro);
}
}
Now I want the annotation processor to report that the constructor for Venue never calls johnny.registerListeners(). How might I do this?
My Annotation processor uses Compiler Tree API in tools.jar, and I've created a code scanner like @Hervian. But scanning like the previous answer lacks the Type info that I need to evaluate expressions. That's what I'm working on now.