Created
January 7, 2015 14:57
-
-
Save freekman/fefba167bd352a635a92 to your computer and use it in GitHub Desktop.
Sample Test with annotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) | |
@java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD}) | |
public @interface MyTestAnnotation { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.clouway.patterns.reflection; | |
import java.lang.reflect.InvocationTargetException; | |
import java.lang.reflect.Method; | |
/** | |
* @ author Ivan Genchev ([email protected]) | |
*/ | |
public class SampleTest { | |
public static class MyAnotherTest { | |
@MyTestAnnotation | |
public void testAddTwoNumbers() { | |
System.out.println("Adding two numbers"); | |
} | |
@MyTestAnnotation | |
public void someMethod() { | |
System.out.println("Some method"); | |
} | |
} | |
public static void main(String[] args) throws InstantiationException, IllegalAccessException { | |
runTests(MyAnotherTest.class); | |
} | |
private static void runTests(Class<?> clazz) throws IllegalAccessException, InstantiationException { | |
Method[] methods = clazz.getDeclaredMethods(); | |
Object o = clazz.newInstance(); | |
Object[] emptyArgs = {}; | |
for (Method each : methods) { | |
if (each.isAnnotationPresent(MyTestAnnotation.class)) { | |
// move to the next method in case when | |
// method parameters are more then zero | |
if (each.getParameterTypes().length != 0) { | |
continue; | |
} | |
try { | |
each.invoke(o, emptyArgs); | |
} catch (InvocationTargetException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment