Skip to content

Instantly share code, notes, and snippets.

@freekman
Created January 7, 2015 14:57
Show Gist options
  • Save freekman/fefba167bd352a635a92 to your computer and use it in GitHub Desktop.
Save freekman/fefba167bd352a635a92 to your computer and use it in GitHub Desktop.
Sample Test with annotations
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
public @interface MyTestAnnotation {
}
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