注释如何与 Java 一起工作?以及如何创建这样的自定义注释:
@Entity(keyspace=':')
class Student
{
@Id
@Attribute(value="uid")
Long Id;
@Attribute(value="fname")
String firstname;
@Attribute(value="sname")
String surname;
// Getters and setters
}
基本上,我需要的是这个 POJO 在持久化时像这样序列化:
dao.persist(new Student(0, "john", "smith"));
dao.persist(new Student(1, "katy", "perry"));
因此,实际生成/持久化的对象是一个 Map<String,String>
像这样:
uid:0:fname -> john
uid:0:sname -> smith
uid:1:fname -> katy
uid:1:sname -> perry
有什么想法可以实现吗?
最佳答案
如果您创建自定义注释,则必须使用 Reflection
API Example Here处理它们。
可以引用How to declare annotation.
以下是 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
和 Target
被称为 meta-annotations
。
RetentionPolicy.RUNTIME
表示要在运行时保留注解,运行时可以访问。
ElementType.METHOD
表示您只能在方法上声明注释,类似地,您可以为类级别、成员变量级别等配置注释。
每个反射类都有方法来获取已声明的注释。
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.
您会发现这些方法适用于 Field
、Method
、Class
类。
例如,在运行时检索指定类上的注解
Annotation[] annos = ob.getClass().getAnnotations();
关于java - 创建自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12257431/