fork(5) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.lang.annotation.ElementType;
  4. import java.lang.annotation.Retention;
  5. import java.lang.annotation.RetentionPolicy;
  6. import java.lang.annotation.Target;
  7. import java.lang.reflect.Method;
  8.  
  9. @Target(ElementType.METHOD)
  10. @Retention(RetentionPolicy.RUNTIME)
  11. @interface Test {
  12. Class expected();
  13. }
  14.  
  15. class TestAnnotationParser {
  16. public <T> void parse(Class<T> clazz, T obj) throws Exception {
  17. Method[] methods = clazz.getMethods();
  18. int pass = 0;
  19. int fail = 0;
  20.  
  21. for (Method method : methods) {
  22. if (method.isAnnotationPresent(Test.class)) {
  23. Test test = method.getAnnotation(Test.class);
  24. Class expected = test.expected();
  25. try {
  26. method.invoke(obj);
  27. pass++;
  28. } catch (Exception e) {
  29. if (Exception.class != expected) {
  30. e.printStackTrace();
  31. fail++;
  32. } else {
  33. pass++;
  34. }
  35. }
  36. }
  37. }
  38. System.out.println("Passed:" + pass + " Fail:" + fail);
  39. }
  40. }
  41.  
  42. class MyTest {
  43.  
  44. @Test(expected = RuntimeException.class)
  45. public void testBlah() {
  46. }
  47. }
  48.  
  49. /* Name of the class has to be "Main" only if the class is public. */
  50. public class Main {
  51. public static void main(String[] args) {
  52. TestAnnotationParser parser = new TestAnnotationParser();
  53. try {
  54. parser.parse(MyTest.class, new MyTest());
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60.  
Success #stdin #stdout 0.1s 380352KB
stdin
Standard input is empty
stdout
Passed:1   Fail:0