mercredi 27 septembre 2023

How to get annotations of an Interface default method with reflection

I thought it would behave the same as with regular methods but I can't seem to find a way. For context, I have an interface that defines some default method implementations including parameters that are extended by some TestNG classes. If those classes are annotated at the class level with the @Test annotation it tries to execute those methods and fails when it tries to inject values. Seems like this is by design based on the responses I got here.

I was attempting the solution provided on that issue but I'm having no luck.

@Override
  @SneakyThrows
  public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
    // See: https://github.com/testng-team/testng/issues/2983
    return methods.stream()
        .filter(
            it -> {
              Method method = it.getMethod().getConstructorOrMethod().getMethod();
              return !method.isAnnotationPresent(Ignore.class) && !method.isDefault();
            })
        .collect(Collectors.toList());
  }

After annotating the Interface with the @Ignore annotation the ethods were not skipped. During debugging it was obvious it was getting empty array of annotations for the method.

I tried adding code as follows trying to get to the declaring class (the interface) and trying there without luck.

        List<IMethodInstance> newMethods= new ArrayList<>();
        for(IMethodInstance it:methods){
          Method method = it.getMethod()
              .getConstructorOrMethod()
              .getMethod();
          Method parentMethod = method.getDeclaringClass().getMethod(method.getName(),
     method.getParameterTypes());
          if(!parentMethod.isAnnotationPresent(Ignore.class)){
            newMethods.add(it);
          }else{
            log.info(String.format("Skipping method %s due to @Ignore annotation!",
     it.getMethod().getMethodName()));
          }
        }
        return newMethods;

AnnotationUtils.findAnnotation(method, Ignore.class) returns null even when the JavaDocs claim it includes interfaces.





Aucun commentaire:

Enregistrer un commentaire