2012-09-04 67 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