4

In the process of writing a Java program doing a lot of logging using java.util.logging (keeping it simple) I was wondering if I could generate the (MyJavaFile.java:123) bit with the java annotation processor at compile time creating static strings containing this information to be used for logging. I am not interested in throwing and investigating an exception at runtime.

I would therefore like to be able to get the line number for an Element found by the annotation processor code eventually written by me to do this (generate a class with string constants including method+line number) but was not able to identify the proper way to do this.

How should "get line number for current source" be done when processing annotations?

  • You could potentially work with the `StackTraceElement`s for the given `Thread.currentThread().getStackTrace()`, for which there is a `StackTraceElement#getLineNumber`. There's also the relatively-newer stackwalking api, which you could look into. – Rogue Sep 07 '22 at 14:06
  • Your question doesn't appear to make sense, perhaps edit it. Specifically: Ordinarily, you log with e.g. `log.warn("Hello")`, and stack traces let you get line numbers if you want it (though, that is slow). Where does the annotation part come in? – rzwitserloot Sep 07 '22 at 14:20
  • It almost sounds like you think you can annotate arbitrary lines. You can't, which makes this question moot. Annotation processors only see signatures (field and method decls), not method bodies. I'm not quite sure what you want, but I'm pretty sure the answer is 'whatever it is, you cannot :('. – rzwitserloot Sep 07 '22 at 14:31
  • @rzwitserloot I have revised the text. I may have misunderstood what is possible. – Thorbjørn Andersen - UFST Sep 07 '22 at 14:50
  • Ah, I see what you want to do now. Annotation Processors _cannot do this_ officially. You could hack it (use APs as a way 'in', using a lot of `--add-opens` and presumptive casting, or use agents, or just fork `javac`, that'll probably be easier. But this is still all incredibly complicated. – rzwitserloot Sep 07 '22 at 14:57
  • If you are interested, we (core dev team, [Project Lombok](https://projectlombok.org)) have been considering adding something like this. We'd accept PRs... – rzwitserloot Sep 07 '22 at 14:59
  • @rzwitserloot Thank you for clarifying that this is not easily done. I have previously been very wary about Lombok because it needs to hook deep into the compiler to do its magic which makes the builds vendor dependant. Is this still so? – Thorbjørn Andersen - UFST Sep 08 '22 at 10:13

0 Answers0