2012-09-04 236 views
5

注释如何与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 

任何想法如何实现这个?

回答

3

如果您创建自定义注释,则必须使用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 { } 

RetentionTarget称为meta-annotations

RetentionPolicy.RUNTIME表示您希望在运行时保留注释,并且您可以在运行时访问它。

ElementType.METHOD表明您只能在方法声明标注同样,你可以配置你的类级别的注释,成员变量水平等

每个反射类有方法来获取所宣注解。

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. 

你会发现本作FieldMethodClass类这些方法。

e.g.To检索注释在运行时出现在指定的类

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

我可以得到getAnnotations)注释(但是我怎么能得到哪些字段或方法相关的注释? – xybrek

+0

您只在Field,Method或Class上调用'getAnnotations()',这是与这些注释相关的字段。另一个betther [示例](http://tutorials.jenkov.com/java-reflection/annotations.html) –

+0

对,我完成了我的代码这个功能 – xybrek