Code replacement with an annotation processor

半世苍凉 提交于 2019-11-27 11:42:52

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 implmements 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 implmements 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!