mardi 19 juillet 2022

How to call all methods in the current package that have a certain @Annotation?

Lets say i have a method in some class in my application's package:

import org.junit.jupiter.api.Test;

@Test
public void testFizBuzz() {
    if (1 != 0) 
       throw new Exception("Test failed");
}

I want to:

  • enumerate all classes/methods in the "current" package
  • find methods tagged with a specified @Annotation
  • construct the class
  • call the (parameterless) method

How can i do this in Java?

In .NET it's easy

Here's how you do it in .NET (in pseudo-Java):

//Find all methods in all classes tagged with @Test annotation, 
//and add them to a list.
List<MethodInfo> testMethods = new ArrayList<>();

//Enumerate all assemblies in the current application domain
for (Assembly a : AppDomain.currentDomain.getAssemblies()) {
   //Look at each type (i.e. class) in the assembly
   for (Type t : a.getTypes()) {
      //Look at all methods in the class. 
      for (MethodInfo m : t.getMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
         //If the method has our @Test annotation defined: add it
         if (m.IsDefined(typeof(org.junit.jupiter.api.Test), true)) 
            testMethods.add(m);
      }
   }
}

And now that we have a List of all methods with the @Test annotation, it's just a matter of calling them:

//Call every test method found above
for (MethodInfo m : testMethods) {
   Object o = Activator.CreateInstance(m.DeclaringType); //Construct the test object
   m.Invoke(o, null); //call the parameterless @Test method
}

What is the JRE equivalent of the above?

Research Effort





Aucun commentaire:

Enregistrer un commentaire