2012-09-04 14 views
5

¿Cómo funciona la anotación con Java? ¿Y cómo puedo crear anotaciones personalizadas así:Crear anotaciones personalizadas

@Entity(keyspace=':') 
class Student 
{ 
    @Id 
    @Attribute(value="uid") 
    Long Id; 
    @Attribute(value="fname") 
    String firstname; 
    @Attribute(value="sname") 
    String surname; 

    // Getters and setters 
} 

Básicamente, lo que necesita tener es serializar este POJO como esto cuando persistido:

dao.persist(new Student(0, "john", "smith")); 
dao.persist(new Student(1, "katy", "perry")); 

De tal manera que, la generada objeto real/PERSISTED es un Map<String,String> así:

uid:0:fname -> john 
uid:0:sname -> smith 
uid:1:fname -> katy 
uid:1:sname -> perry 

Alguna idea de cómo implementar esto?

Respuesta

3

Si crea anotaciones personalizadas, deberá usar Reflection API Example Here para procesarlas. Puede referir How to declare annotation. Así es como se ve la declaración de anotación de ejemplo en java.

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 { } 

Retention y Target son conocidos como meta-annotations.

RetentionPolicy.RUNTIME indica que desea conservar la anotación en tiempo de ejecución y puede acceder a ella en tiempo de ejecución.

ElementType.METHOD indica que puede declarar la anotación sólo en los métodos de manera similar puede configurar su anotación de nivel de clase, nivel variable miembro etc.

Cada clase tiene Reflexión métodos para obtener las anotaciones que se declaran.

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) getAnnotation(Class<T> annotationClass) 
Returns this element's annotation for the specified type if such an annotation is present, else null. 

public Annotation[] getDeclaredAnnotations() 
Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. (Returns an array of length zero if no annotations are directly present on this element.) The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers. 

Encontrará estos métodos actuales para Field, Method, Class clases.

e.g.To recuperar anotaciones presentan en la clase especificada en tiempo de ejecución

Annotation[] annos = ob.getClass().getAnnotations(); 
+0

puedo conseguir la anotación con getAnnotations() Sin embargo, ¿cómo puedo conseguir qué campo o método relacionado con la anotación? – xybrek

+0

Está llamando a 'getAnnotations()' en 'Campo',' Método' o 'Clase' solamente, por lo que es el campo que está relacionado con estas anotaciones. Otro ejemplo [ejemplo] (http://tutorials.jenkov.com/java-reflection/annotations.html) –

+0

Bien, terminé mi código para esta función – xybrek

Cuestiones relacionadas