Reputation: 35276
How does annotation work with Java? And how can I create custom annotations like this:
@Entity(keyspace=':')
class Student
{
@Id
@Attribute(value="uid")
Long Id;
@Attribute(value="fname")
String firstname;
@Attribute(value="sname")
String surname;
// Getters and setters
}
Basically, what I need to have is this POJO be serialized like this when persisted:
dao.persist(new Student(0, "john", "smith"));
dao.persist(new Student(1, "katy", "perry"));
Such that, the actual generated/persisted object is a Map<String,String>
like this:
uid:0:fname -> john
uid:0:sname -> smith
uid:1:fname -> katy
uid:1:sname -> perry
Any ideas how to implement this?
Upvotes: 6
Views: 4562
Reputation: 19185
If you create custom annotations you will have to use Reflection
API Example Here to process them.
You can refere How to declare annotation.
Here is how example annotation declaration in java looks like.
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
and Target
are known as meta-annotations
.
RetentionPolicy.RUNTIME
indicates that you want to retain the annotation at runtime and you can access it at runtime.
ElementType.METHOD
indicates that you can declare annotation only on methods similarly you can configure your annotation for class level, member variable level etc.
Each Reflection class has methods to get annotations which are declared.
public <T extends Annotation> T 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.
You will find these methods present for Field
, Method
,Class
classes.
e.g.To retrieve annotations present on specified class at run time
Annotation[] annos = ob.getClass().getAnnotations();
Upvotes: 3