Monday, June 18, 2012

Java Annotation

It's a great technology that helps your class focuses on what should be done, reduces the complexity of your class and makes your code clean. Here let's go through our own JUnit example to see how annotations work.

Here we create our own annotation:

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {

}

Of course, the annotations don't do anything by themselves. We need a tool to process these annotations:
import java.lang.reflect.*;

public class TestRunner {

    public static void runTests(Object obj) {
        try {
            Class cl = obj.getClass();
            for (Method m : cl.getDeclaredMethods()) {
                Test t = m.getAnnotation(Test.class);
                if (t != null) {
                    m.invoke(obj, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Now we can write our own test cases:

public class UnitTest {

    public UnitTest() {
        TestRunner.runTests(this);
    }
 
    @Test
    public void testCase1() {
        System.out.println("Test Case 1");
    }
 
    @Test
    public void testCase2() {
        System.out.println("Test Case 2");
    }
 
    public static void main(String[] args) {
        new UnitTest();
    }
}