A sample Java test runner using annotations
I have found this toy code on java.sun.com that describes how Java annotations could be used to write a simple Test runner. This script gets as argument the name of a class and tries to execute all the methods of that class that are annotated as @Test.
The interesting aspect of this code is that is shows clearly how annotations can be used to execute/manipulate source code.
import java.lang.reflect.*; public class RunTests { public static void main(String[] args) throws Exception { int passed = 0, failed = 0; for (Method m : Class.forName(args[0]).getMethods()) { if (m.isAnnotationPresent(Test.class)) { try { m.invoke(null); passed++; } catch (Throwable ex) { System.out.printf( "Test %s failed: %s %n", m, ex.getCause() ); failed++; } } } System.out.printf("Passed: %d, Failed %d%n", passed, failed); } }



