Você está na página 1de 24

Java Annotations

Rubby Casallas Grupo de Construccin de Software Universidad de los Andes

Referencias
http://www128.ibm.com/developerworks/java/library/jannotate1/ http://download.oracle.com/javase/1,5.0/docs /guide/language/annotations.html

Meta-Data
Meta-data es data about data Existe desde Java 5.0 Mecanismo para adicionar anotaciones Anotaciones son modificadores que se pueden adicionar al cdigo y aplicarlos sobre declaraciones de tipos, constantes, mtodos, atributos, etc. Existen anotaciones predefinidas y tipos de anotaciones definidas por el desarrollador Java 5.0 ofrece un mecanismo para acceder a las anotaciones va introspeccin
3

Meta-Data
Informacin adicional (anotaciones) atadas a los elementos de un programa (atributos, mtodos, clases, etc.). Ejemplo: Xdoclet
// @ejb.name = Task

La semntica de las anotaciones puede ser desde documentacin hasta cambiar el comportamiento del mtodo.
4

Para qu sirve?
Documentacin:
ejemplo: javadoc, @uml

Verificaciones en el momento de la compilacin:


ejemplo: Verificar consistencia entre mtodos o clases

Anlisis de cdigo
ejemplo: xdoclet

Guiar y mejorar la generacin de cdigo


5

Conceptos Bsicos
Marker annotations:
No tienen variables Se identifican por un nombre No incluye informacin adicional Ejemplo: @MarkerAnnotation

Conceptos Bsicos
Single-value annotations:
Parecidas a las marcas Proveen una informacin simple Ejemplo:
@SingleValueAnnotation("my data")

Conceptos Bsicos
Full annotations:
Tienen atributos y valores Ejemplo:
@FullAnnotation(var1="data value 1", var2="data value 2", var3="data value 3")

Conceptos Bsicos
@TODOItems({ // Arreglo de anotaciones @TODO( severity=TODO.CRITICAL, item="Add functionality to calculate .., assignedTo="Brett McLaughlin" ), @TODO( severity=TODO.IMPOTANT, item="Print usage message to screen .., assignedTo="Brett McLaughlin" ), @TODO( severity=TODO.LOW, item="Roll a new website page with... , assignedTo="Jason Hunter" ) })

Anotaciones Predefinidas
Override annotation Deprecated annotation SuppressWarnings annotation

10

Override annotation
Solo se puede utilizar en mtodos Es equivalente a un comentario que indica que el mtodo anotado sobrecarga el mtodo de la superclase. La diferencia con el comentario e squ eel compilador ahace un chequeo

11

package com.oreilly.tiger.ch06; public class OverrideTester { public OverrideTester() { } @Override public String toString() { return " [Override Tester Implementation]"; } @Override public int hashCode() { return toString().hashCode(); } }

12

Deprecated annotation

package com.oreilly.tiger.ch06; public class DeprecatedClass { @Deprecated public void doSomething() { // some code } public void doSomethingElse() { // This method presumably does what doSomething() does, but better } }

13

SuppressWarnings annotation
til en versiones de java que no soportan ciertos nuevos hechos. Por ejemplo generics.
@SuppressWarnings(value={"unchecked"}) public void nonGenericsMethod() { List wordList = new ArrayList(); // no typing information on the List wordList.add("foo"); // causes error on list addition }
14

Anotaciones definidas por el desarrollador


Definicin:
package com.oreilly.tiger.ch06; public @interface TODO { public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION }; Severity severity() default Severity.IMPORTANT; String item(); String assignedTo(); String dateAssigned(); }

15

Anotaciones definidas por el desarrollador


Utilizacin:
@TODO( item="Figure out the amount of interest per month", assignedTo="Brett McLaughlin", dateAssigned="08/04/2004" ) public void calculateInterest(float amount, float rate) {}

16

Anotaciones sobre anotaciones


Definiendo sobre cul elemento del lenguaje va la anotacin:
package java.lang.annotation; public enum ElementType { TYPE, // Class, interface, or enum (but not annotation) FIELD, // Field (including enumerated values) METHOD, // Method (does not include constructors) PARAMETER, // Method parameter CONSTRUCTOR, // Constructor LOCAL_VARIABLE, // Local variable or catch clause ANNOTATION_TYPE, // Annotation Types (meta-annotations) PACKAGE // Java package }

17

Anotaciones sobre anotaciones


@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE}) public @interface TODO { String value(); }

18

Retencin de las anotaciones


Se puede decidir:
Que el compilador procese las anotaciones pero no las incluya en el bytecode Que las anotaciones se queden en el bytecode Que las anotaciones se puedan utilizar en tiempo de ejecucin
package java.lang.annotation; public enum RetentionPolicy { SOURCE, // Annotation is discarded by the compiler CLASS, // Annotation is stored in the class file, but ignored by the VM RUNTIME // Annotation is stored in the class file and read by the VM }
19

Retencin de las anotaciones


Definicin de la poltica para una anotacin:

@Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings {// body }

20

Javadoc de las anotaciones

package com.oreilly.tiger.ch06; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.RUNTIME) public @interface InProgress { }

21

public class Account { ... @Transactional(kind=Required) public void credit(float amount) { ... } @Transactional(kind=Required) public void debit(float amount) { ... } public float getBalance() { ... } ... }

pointcut execution( @Transactional * *.*(..)); Por ahora el lenguaje no permite utilizar propiedades de las anotaciones para definir los pointcuts:
pointcut execution(@Transactional(kind==RequiredNew) *.*(..))

22

pointcut transactedOps(Transactional tx) : execution(@Transactional * *.*(..)) && @annotation(tx);

Object around (Transactional tx) : transactedOps(tx) { if (tx.value() == Required) { // implement the required transaction behavior } else if(tx.value() == RequiredNew) { // implement the required-new transaction // behavior } ... }

23

Utilizacin de AOP para suministrar Anotaciones


declare annotation : * Account.*(..) : @Authenticated(permission="banking");

24

Você também pode gostar