2012-09-04 14 views
5

एनोटेशन जावा के साथ कैसे काम करता है? और कैसे मैं इस तरह कस्टम एनोटेशन बना सकते हैं:कस्टम एनोटेशन बनाना

@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. रेफर कर सकते हैं यहां जावा में उदाहरण एनोटेशन घोषणा कैसा दिखता है।

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 और Targetmeta-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. 

आप इन तरीकों Field, Method, Class कक्षाओं के लिए वर्तमान मिल जाएगा।

पुनः प्राप्त e.g.To एनोटेशन रन समय पर निर्दिष्ट वर्ग पर पेश

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

मैं getAnnotations साथ एनोटेशन() प्राप्त कर सकते हैं जो क्षेत्र या विधि एनोटेशन से संबंधित मैं तथापि कैसे मिल सकता है? – xybrek

+0

आप 'फ़ील्ड', 'विधि' या' कक्षा 'पर केवल' getAnnotations() 'को कॉल कर रहे हैं, इसलिए यह क्षेत्र इन एनोटेशन से संबंधित है। एक और betther [उदाहरण] (http://tutorials.jenkov.com/java-reflection/annotations.html) –

+0

ठीक है, मैंने इस फ़ंक्शन के लिए अपना कोड समाप्त कर दिया – xybrek

संबंधित मुद्दे