Bug in ClassFile API?

Archie Cobbs archie.cobbs at gmail.com
Wed Nov 12 16:20:14 UTC 2025


Wait, I think I just figured this out... the annotation is on the code, not
the method...

Nevermind! Thanks.

On Wed, Nov 12, 2025 at 10:17 AM Archie Cobbs <archie.cobbs at gmail.com>
wrote:

> I think I found a bug in the ClassFile API but since I'm new to it, before
> creating one in Jira, I wanted to double-check I'm not doing something
> stupid... could someone please confirm?
>
> Consider this simple test class:
>
> import java.lang.annotation.*;
> import java.lang.classfile.*;
> import java.nio.file.Path;
>
> public class Test {
>
>     public static void main(String[] args) throws Exception {
>         final String filename = args.length > 0 ? args[0] :
> "Example.class";
>         final Path path = Path.of(filename);
>         final ClassFile classFile = ClassFile.of();
>         final ClassModel classModel = classFile.parse(path);
>         classModel.forEach(classElement -> {
>             switch (classElement) {
>             case MethodModel method when
> method.methodName().equalsString("<init>") ->
>                 System.out.println(String.format("%s: method \"%s\":
> runtime visible type annotations: %s",
>                   filename, method.methodName(),
> method.findAttribute(Attributes.runtimeVisibleTypeAnnotations())));
>             default -> { }
>             }
>         });
>     }
> }
>
> class Example {
>     Example(Object o) {
>         String s = (@Anno String)o;
>     }
> }
>
> @Retention(RetentionPolicy.RUNTIME)
> @Target(ElementType.TYPE_USE)
> @interface Anno { }
>
> If you compile and run this test it doesn't find any type annotation
> attribute on the Example constructor:
>
> $ javac Test.java && java Test
> Example.class: method "<init>": runtime visible type annotations:
> Optional.empty
>
> Yet javap shows that there is one (as expected):
>
> $  javap -verbose Example
> ...
>   Example(java.lang.Object);
>     descriptor: (Ljava/lang/Object;)V
>     flags: (0x0000)
>     Code:
>       stack=1, locals=3, args_size=2
>          0: aload_0
>          1: invokespecial #1                  // Method
> java/lang/Object."<init>":()V
>          4: aload_1
>          5: checkcast     #7                  // class java/lang/String
>          8: astore_2
>          9: return
>       LineNumberTable:
>         line 24: 0
>         line 25: 4
>         line 26: 9
>       RuntimeVisibleTypeAnnotations:
>         0: #15(): CAST, offset=5, type_index=0
>           Anno
>
> Thanks,
> -Archie
>
> --
> Archie L. Cobbs
>


-- 
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20251112/2496161c/attachment.htm>


More information about the core-libs-dev mailing list