Scala, Maven, and preprocessors

前端 未结 4 527
梦毁少年i
梦毁少年i 2021-01-20 00:46

I know all of the philosophical arguments against preprocessors and macros in Java. I don\'t agree that just because some may abuse a language feature, it should be excluded

4条回答
  •  清歌不尽
    2021-01-20 01:28

    You can use the compiler API to do this, but be careful. The "rules" for annotation processors/compiler plugins state that they are not supposed to modify the class being generated. Sun/Oracle may enforce this at anytime.

    For now, have a peek at http://projectlombok.org. It uses the compiler API to generate getters, setters and so forth. They have source code that you could use as a model, or you could contribute handlers to them.

    you could probably do something like the following:

    public class Foo {
      @FileName private static String fileName;
      @LineNumber private static int lineNumber;
      ...
      public void foo() {
         log(fileName, lineNumber, "some message");
      }
    }
    

    Then have the annotation processor change the fileName and lineNumber references to the actual file/line.

    Just be aware that this could break with later JDK versions. I don't know if Sun/Oracle will actually enforce the "don't modify the class being generated" rule, but they could.

提交回复
热议问题