2012-09-04 43 views
5

Chú thích hoạt động với Java như thế nào? Và làm thế nào tôi có thể tạo các chú thích tùy chỉnh như thế này:Tạo chú thích tùy chỉnh

@Entity(keyspace=':') 
class Student 
{ 
    @Id 
    @Attribute(value="uid") 
    Long Id; 
    @Attribute(value="fname") 
    String firstname; 
    @Attribute(value="sname") 
    String surname; 

    // Getters and setters 
} 

Về cơ bản, những gì tôi cần phải có được POJO này được tuần tự như thế này khi vẫn kiên trì:

dao.persist(new Student(0, "john", "smith")); 
dao.persist(new Student(1, "katy", "perry")); 

như vậy đó, tạo/tiếp tục tồn tại đối tượng thực tế là một Map<String,String> như sau:

uid:0:fname -> john 
uid:0:sname -> smith 
uid:1:fname -> katy 
uid:1:sname -> perry 

Bất kỳ ý tưởng nào về cách triển khai tính năng này?

Trả lời

3

Nếu bạn tạo chú thích tùy chỉnh, bạn sẽ phải sử dụng Reflection API Example Here để xử lý chúng. Bạn có thể yêu cầu How to declare annotation. Đây là cách khai báo chú thích ví dụ trong 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 được gọi là meta-annotations.

RetentionPolicy.RUNTIME cho biết rằng bạn muốn giữ lại chú thích khi chạy và bạn có thể truy cập chú thích khi chạy.

ElementType.METHOD chỉ ra rằng bạn có thể khai báo chú thích chỉ về phương pháp tương tự bạn có thể cấu hình chú thích của mình cho cấp lớp, thành viên biến mức, vv

Mỗi lớp Reflection có phương pháp để có được chú thích được công bố.

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. 

Bạn sẽ tìm thấy những phương pháp hiện nay cho Field, Method, Class lớp.

e.g.To lấy chú thích trình bày trên lớp quy định tại thời gian chạy

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

tôi có thể nhận được chú thích với getAnnotations() Tuy nhiên làm thế nào tôi có thể nhận được mà lĩnh vực hoặc phương pháp liên quan đến việc chú giải? – xybrek

+0

Bạn đang gọi 'getAnnotations()' trên 'Field',' Method' hoặc 'Class' chỉ để trường có liên quan đến các chú thích này. Một ví dụ khác [ví dụ] (http://tutorials.jenkov.com/java-reflection/annotations.html) –

+0

Phải, tôi đã hoàn thành mã của mình cho hàm này – xybrek

Các vấn đề liên quan