Thursday, November 04, 2010

Annotation Hikayesi

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

package test.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public @interface Test {
public enum LEVEL {

LEVEL level() default LEVEL.TRIVIAL;
} nin yaptigi bir annotation tanimlamak.
RetentionPolicy.RUNTIME ile bu annotation'in RUNTIME'da etkin olmasini sagliyoruz.
LEVEL isimli bir enum tip tanimi yapiyoruz.
Bir de bu annotation icin LEVEL tipinde level isimli bir element tanimliyoruz.

package test.annotation;

import test.annotation.Test.LEVEL;

public class Foo {
   @Test (level = LEVEL.SERIOUS)
   public static void m1() { }
   public static void m2() { }
   @Test (level = LEVEL.SERIOUS)
   public static void m3() {
       throw new RuntimeException("Boom");
   public static void m4() { }
   public static void m5() { }
   public static void m6() { }
   @Test (level = LEVEL.CRITICAL)
   public static void m7() {
       throw new RuntimeException("Crash");
   public static void m8() { }

}, bizim birazdan yazacagimiz Tester class'in uzerinde kosacagi class. Bazi metodlarini annotate etmisiz ve level specify etmisiz. m1 ve m3 SERIOUS, m7 CRITICAL ve m5 de default TRIVIAL level'inda taglamisiz.

package test.annotation;

import java.lang.reflect.Method;

public class RuntTests {
 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)) {    
    Test annotation = m.getAnnotation(Test.class);
    if (annotation.level() == Test.LEVEL.valueOf(args[1]))
     try {
     } catch (Throwable ex) {
      System.out.printf("Test %s failed: %s %n", m, ex.getCause());
  System.out.printf("Passed: %d, Failed %d%n", passed, failed);

RunTests bizim Tester classimiz. Disardan iki tane parametre aliyor. Ilk'i testin kosulacagi class, digeri ise hangi level'daki method'larin call edilecegini belirtiyor.
Process edilen class'in metodlarindan Test annotation'i iceren ve parametre olarak verilen level'daki metodlar call ediliyor. Asagida sonuclar :

java test.annotation.RuntTests test.annotation.Foo MINOR
Passed: 0, Failed 0

java test.annotation.RuntTests test.annotation.Foo CRITICAL
Test public static void test.annotation.Foo.m7() failed: java.lang.RuntimeException: Crash
Passed: 0, Failed 1

java test.annotation.RuntTests test.annotation.Foo SERIOUS
Test public static void test.annotation.Foo.m3() failed: java.lang.RuntimeException: Boom
Passed: 1, Failed 1

Bir kac link verip burda noktaliyalim.

No comments: