Code replacement with an annotation processor

A bit late :), but one solution could be to use Byte Buddy's transformer as part of the build process. See eg https://github.com/raphw/byte-buddy/tree/master/byte-buddy-maven-plugin.


The intention behind the annotation processor is to allow a developer to add new classes, not replace existing classes. That being said, there is a bug that allows you to add code to existing classes. Project Lombok has leveraged this to add getter and setter (among other things) to your compiled java classes.

The approach I have taken to 'replace' methods/fields is either extend from or delegate to the input class. This allows you to override/divert calls to the target class.

So if this is your input class:

InputImpl.java:

public class InputImpl implements Input{
    public void foo(){
        System.out.println("foo");
    }
    public void bar(){
        System.out.println("bar");
    }
}

You could generate the following to "replace" it:

InputReplacementImpl.java:

public class InputReplacementImpl implements Input{

    private Input delegate;

    //setup delegate....

    public void foo(){
        System.out.println("foo replacement");
    }
    public void bar(){
        delegate.bar();
    }
}

This begs the question, how do you reference InputReplacementImpl instead of InputImpl. You can either generate some more code to perform the wrapping or simply call the constructor of the code expected to be generated.

I'm not really sure what your question is, but I hope this sheds some light on your issues.