注释如何与Java一起使用?我如何创建这样的自定义注释:
@Entity(keyspace=':')
class Student
{
@Id
@Attribute(value="uid")
Long Id;
@Attribute(value="fname")
String firstname;
@Attribute(value="sname")
String surname;
// Getters and setters
}
Run Code Online (Sandbox Code Playgroud)
基本上,我需要拥有的是这个POJO在持久化时被序列化:
dao.persist(new Student(0, "john", "smith"));
dao.persist(new Student(1, "katy", "perry"));
Run Code Online (Sandbox Code Playgroud)
这样,实际生成/持久化的对象是Map<String,String>这样的:
uid:0:fname -> john
uid:0:sname -> smith
uid:1:fname -> katy
uid:1:sname -> perry
Run Code Online (Sandbox Code Playgroud)
任何想法如何实现这一点?
如果您创建自定义注释,则必须使用此处的ReflectionAPI 示例来处理它们。您可以参考如何声明注解。
下面是 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 { }
Run Code Online (Sandbox Code Playgroud)
Retention并被Target称为meta-annotations.
RetentionPolicy.RUNTIME表示要在运行时保留该注解,并且可以在运行时访问它。
ElementType.METHOD表示您只能在方法上声明注释,类似地您可以为类级别、成员变量级别等配置注释。
每个 Reflection 类都有获取声明的注释的方法。
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.
Run Code Online (Sandbox Code Playgroud)
您会发现这些方法适用于Field、Method、Class类。
例如检索运行时指定类上存在的注释
Annotation[] annos = ob.getClass().getAnnotations();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3606 次 |
| 最近记录: |