0

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.

Charlweed
  • 1,517
  • 2
  • 14
  • 22
  • Show what you have so far. If you don't have an annotation processor already, look up a tutorial on how to create one. – Vince Oct 25 '17 at 18:14
  • You will need to write your own annotation processor. By the way, I would say that the annotation processor should not warn at the location you have marked in your code, but in the constructor for `Musician`. As the code is written, the `Musician` object is ill-formed (only partially initialized) at the end of its constructor. It is better style to fully initialize an object in its own constructor rather than depending on clients to call extra methods after calling the constructor. That is the fix that the annotation processor should suggest, or the location at which it should warn. – mernst Oct 27 '17 at 03:09

0 Answers0