jeudi 22 septembre 2022

Java Method.getAnnotation(Class?> annotation) returns null when annotation is present on the method

So I have this annotation ...

package com.github.benchmarkr.annotation;

// IMPORTS

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Benchmark {
}

It's used to mark a method in a class as a benchmarking test. So I have this class ...

// IMPORTS ...

public class LexerBenchmark {
  @Benchmark
  public void test() {

  }
}

I run the benchmark scanner in debug mode and stop at a point in which I have this classesInPackage variable which is a list of all the discovered classes that fall within a target package. I see the one class shown above (LexerBenchmark) in that list at index 101.

So in the debugger I do classesInPackage.get(101).getDeclaredMethods() and sure enough see my one declared method.

I then do classesInPackage.get(101).getDeclaredMethods()[0].getAnnotations() and see my annotation (com.github.benchmarkr.annotation.Benchmark) in that list.

So I run classesInPackage.get(101).getDeclaredMethods()[0].getAnnotation(Benchmark.class) and I get null. It's weird but seems like it could have had something to do with the fact that the module for the Benchmark.class on the method seemed to be different than the one referenced directly (see the screenshots below).

Things get really weird when I use the same exact value from that list ...

classesInPackage
  .get(101)
  .getDeclaredMethods()[0]
  .getAnnotation(
    classesInPackage
    .get(101)
    .getDeclaredMethods()[0]
    .getAnnotations()[0]
    .getClass()
  )

and I still get null. How could that be possible?

Here are some images from my debugger... Benchmark.class LexerBenchmark.test Method LexerBenchmark.test.getAnnotations() NullResult WeirdNullResult





Aucun commentaire:

Enregistrer un commentaire