Muito importante para que procedimentos padrão sejam efetuados por alguma aplicação e muito útil ao desenvolvimento no que diz respeito a organização e execução de processos de forma simples e bem estrturada, as annotations são simples de serem desenvolvidas. É preciso programar de forma clara cada vez mais, trabalho em equipe é regra adotada dez da mais simples à mais poderosa das organizações.
Vou explicar aqui e indicar fontes para o desenvolvimento de suas próprias annotations. No site da SUN, no link abaixo vocês poderão conferir um exemplo completo e bem explicado. Os códigos abaixo (retirados do exemplo) são auto-explicativos para qualquer programador Java.
Lembrando que a especificação é do Java 5:
/**
* Describes the Request-For-Enhancement(RFE) that led
* to the presence of the annotated API element.
*/
public @interface RequestForEnhancement {
int id();
String synopsis();
String engineer() default "[unassigned]";
String date(); default "[unimplemented]";
}
@RequestForEnhancement(
id = 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }
/**
* Indicates that the specification of the annotated API element
* is preliminary and subject to change.
*/
public @interface Preliminary { }
@Preliminary public class TimeTravel { ... }
/**
* Associates a copyright notice with the annotated API element.
*/
public @interface Copyright {
String value();
}
@Copyright("2002 Yoyodyne Propulsion Systems")
public class OscillationOverthruster { ... }
====== TESTE
import java.lang.annotation.*;
/**
* Indicates that the annotated method is a test method.
* This annotation should be used only on parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
public class Foo {
@Test public static void m1() { }
public static void m2() { }
@Test public static void m3() {
throw new RuntimeException("Boom");
}
public static void m4() { }
@Test public static void m5() { }
public static void m6() { }
@Test public static void m7() {
throw new RuntimeException("Crash");
}
public static void m8() { }
}
Here is the testing tool:
import java.lang.reflect.*;
public class RunTests {
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)) {
try {
m.invoke(null);
passed++;
} catch (Throwable ex) {
System.out.printf("Test %s failed: %s %n", m, ex.getCause());
failed++;
}
}
}
System.out.printf("Passed: %d, Failed %d%n", passed, failed);
}
}
FONTE: Http://java.sun.com Annotations (by Java 5 docs guide)
Nenhum comentário:
Postar um comentário