创建自定义注释 [英] Creating custom annotations
问题描述
如何工作的注释与Java?我怎么能这样创建定制注释:
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
}
基本上,我需要的是这个POJO被序列化这样的坚持,当:
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"));
这样,实际产生/持久化的对象是一个地图<字符串,字符串>
是这样的:
uid:0:fname -> john
uid:0:sname -> smith
uid:1:fname -> katy
uid:1:sname -> perry
任何想法如何实现这一点?
Any ideas how to implement this?
推荐答案
如果您创建自定义的注解,你将不得不使用反射
API的例此处处理。
您可以参考,如何声明注释。
下面是在Java注解的例子声明的样子。
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 { }
保留
和目标
被称为元注释
。
RetentionPolicy.RUNTIME
表示要保留在运行时的注释,你可以在运行时访问它。
RetentionPolicy.RUNTIME
indicates that you want to retain the annotation at runtime and you can access it at runtime.
ElementType.METHOD
表示只能在方法声明注释同样可以配置类级别的注释,成员变量的水平等。
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) 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.
您会发现字段
,方法
,类这些方法present
类。
e.g.To检索注释present上指定的类在运行时
e.g.To retrieve annotations present on specified class at run time
Annotation[] annos = ob.getClass().getAnnotations();
这篇关于创建自定义注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!