简体   繁体   中英

Annotating generated Java source nullability (for Kotlin)

I am generating Java source files for my project using a source generation tool ( ). However, I am writing most, if not all of my code, in Kotlin.

Kotlin already offers great Java interop , so using the generated sources is not a problem. However, because of how Kotlin brings Java's nullable types into a null-safe system , I lose most of the null-safety that I use Kotlin for. At the very best I have warnings of platform types (make type explicit to avoid subtle bugs); at the worst I have unexpected crashes and subtle bugs.

Kotlin does, however, respect nullability annotations , such as JSR-305, FindBugs, Lombok, Eclipse, and JetBrains's respective forms of @Nullable / @NonNull , bringing those in as the appropriate non-null type or optional.

Because the code is generated and I have access to the source (and understand how it works), I know which functions can/not return null , and want to annotate them as such so they include neatly into my null-safe code. However, I cannot add annotations directly into the code, as it is generated during the build step and would overwrite any manual changes.

Is it possible to / what is the best way to annotate the nullability of generated java sources for the purpose of use in null-safe code?

The best way would be to modify the source code generator so that it includes the annotations that you require.

If you can't modify the generator (eg because the generator is proprietary and you don't have its source code) then you can do this using bytecode engineering. For example, this page on the ASM site gives one way to do it:

Of course, in either case you need some way to tell the tool (the generator, the bytecode rewriter, whatever) which methods should be annotated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM