[code-reflection] RFR: Add sample annotation processor using code models [v2]

Maurizio Cimadamore mcimadamore at openjdk.org
Fri Sep 12 16:26:32 UTC 2025


> This change adds a new sample of an annotation processor that uses code models to:
> * reject unsupported methods (e.g. `System.gc`, `System.exit`)
> * reject unsupported language construct (e.g. `try`, `throw`)
> 
> The annotation processor is somewhat configurable, and can be used by developers as an initial sketch upon which to build more custom compile-time checks.
> 
> When using the annotation processor to compile this:
> 
> 
> class Foo {
>    @CodeReflection
>    void test1() {
>       System.exit(1);
>    }
> 
>     @CodeReflection
>     void test2() {
>         System.gc();
>     }
> 
>     @CodeReflection
>     void test3() {
> 
>        try {
>            test2();
>        } finally {
>            test3();
>        }
> 
>     }
> }
> 
> 
> The following error messages are generated:
> 
> 
> Foo.java:5: error: System.exit not supported in reflectable methods
>    void test1() {
>         ^
> Foo.java:10: error: System.gc not supported in reflectable methods
>     void test2() {
>          ^
> Foo.java:15: error: try/catch statement not supported in reflectable methods
>     void test3() {
>          ^
> 
> 
> When putting this together, I noted some issues, reported below:
> 
> * javac was failing to execute annotation processors that depended on `jdk.incubator.code` module
> * obtaining the model from a method that contains attribution errors crashed the annotation processor
> * some packages (e.g. the ones in java.base) are not exported to the dynamic module layer's `jdk.incubator.code`
> * it is not possible to report the message at a more accurate location because the `Messager` API does not allow for this
> 
> Many thanks to @lahodaj for the invaluable help when fighting with module layers :-)

Maurizio Cimadamore has updated the pull request with a new target base due to a merge or a rebase. The pull request now contains six commits:

 - Merge branch 'code-reflection' into codemodel_anno_processor
 - Tweak annotation processor readme guide
 - Tweak documentation
 - Fix test
   Fix JavacFileManager.getServiceLoader
 - Add test
   Make sure java.base packages are exported to dynamic layer's module
 - Initial push

-------------

Changes: https://git.openjdk.org/babylon/pull/554/files
  Webrev: https://webrevs.openjdk.org/?repo=babylon&pr=554&range=01
  Stats: 385 lines in 9 files changed: 370 ins; 0 del; 15 mod
  Patch: https://git.openjdk.org/babylon/pull/554.diff
  Fetch: git fetch https://git.openjdk.org/babylon.git pull/554/head:pull/554

PR: https://git.openjdk.org/babylon/pull/554


More information about the babylon-dev mailing list