开发者

Java: How might one go about generating custom compiler warnings for method usages?

I've been doing some work with annotation processing, and it would be really helpful to be able to warn the user about using certain annotated methods. This is basically creating a custom version of the @Deprecated annotation. I thought a g开发者_如何学编程ood place to start might be the actual annotation processor for @Deprecated, but I can't seem to locate it. :_

(Note that this is similar, but not the same as How to intentionally cause a custom java compiler warning message?)

Thanks!


Think of some of the code inspection warnings like passing null into a varargs method.

For this use case, look at the Checker Framework for existing checkers (like the nullness checker) and how to create custom checkers (or other type annotation processors).

https://checkerframework.org/

I use this tool and its bundled checkers and like it very much.

Without knowing exactly what you have in mind, I wouldn't be surprised if some of the checkers already address some of your ideas. You may be able to create some pluggable types to address your other ideas. At the very least, it might give you some ideas on how to or how not to approach what you want to do.


Thanks to everyone for their feedback. Looking into the compiler API, it's definitely doable (but not so simple). This article provided a good start for the compiler API. I think in the future I will look into writing an extensible rule checker. Attempting to hijack the @Deprecated annotation, by the way, will not work, as inside of the compiler it is removed along with the other "platform annotations".

For now, I'm going with the rather coarse solution of bludgeoning the programmer with a verbose checked exception. While it does clutter the code, it also avoids the complexity of actually analyzing their intent. Something like:

try {
    doWork(workUnit, 15, Style.STRICT);
} catch (MakeSureYouOverrodeEverythingYouWantedToFirst warning) {
    ; // will never actually reach here, but you have been warned!
}

If the programmer fails to do as instructed, the output of their program can be pseudorandomly buggy, and hence rather tedious to debug. And while this solution is certainly a frowned upon hack of exception handling (including by me), it rather simply fullfils my needs.

Besides, the extra effort just might encourage the programmer to actually do what they're supposed to!

I'm still interested in hearing other ideas, if you have one.


The annotation processor is in the javac, you can find the source in OpenJDK. However, itsn't not designed to be extensible.

What you are better off doing is to use code analysis like FindBugs or PMD as these are designed to be extended and have your build fail if certain conditions fail.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜