Tôi đang thực hiện một bộ xử lý chú thích để đảm bảo rằng các yếu tố được đánh dấu bằng một chú thích là trường hợp của một lớp mà thực hiện một giao diện nhất định, hoặc là sử dụng các loại mà thực hiện một giao diện nhất định:Cách xử lý chú thích bằng @Target (ElementType.TYPE_USE)?
@Documented
@Target(value = { ElementType.PARAMETER, ElementType.TYPE_USE })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface AuditSubject {
}
public interface Auditable {
// methods that provide data for writing a log entry...
}
public class Report implements Auditable {
}
Đối với các phần tử được chú thích, một mục nhật ký phải được tạo sau khi thực hiện phương thức (sử dụng AOP). Ví dụ:
@CreateLogEntry
public Result persist(@AuditSubject Report newReport) {
// A log entry must be created with the incoming newReport.
}
@CreateLogEntry
public UpdateResult<@AuditSubject Report> update(Report update) {
// A log entry must be created with the updated report which is not the same instance as 'update' (cannot use it).
}
@CreateLogEntry
public Result persistBatch(List<@AuditSubject Report> batch) {
// A log entry must be created for each element in 'batch' after this method execution.
}
Mục nhập nhật ký phải được tạo với điều kiện Báo cáo thực hiện Kiểm tra; nếu không, ngoại lệ thời gian chạy được ném (Yikes, tôi quên triển khai giao diện!). Vì vậy, bộ xử lý chú thích giúp để nắm bắt những sai lầm lập trình viên tại thời gian biên dịch. Cho đến nay tôi đã thành công trong việc kiểm tra tất cả các sử dụng trong các tham số, nhưng không phải trong sử dụng loại. Các mã có liên quan từ bộ vi xử lý chú thích như sau:
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element annotated : roundEnv.getElementsAnnotatedWith(AuditSubject.class)) {
// Only prints elements with ElementKind.PARAMETER)!
this.messager.printMessage(Kind.NOTE, TextUtils.replaceParams("annotated: {} ; Kind : {} ; enclosing : {}", annotated, annotated.getKind(), annotated.getEnclosingElement()));
if (annotated.getKind() == ElementKind.PARAMETER) {
// Code here works as expected, raises errors for annotated parameters of classes that don't implement Auditable.
} else if (annotated.getKind() == ElementKind.WHAT_TO_USE) {
// What ElementKind do I need to use here?
}
}
return false;
}
yếu tố Chỉ chú thích với loại ElementKind.PARAMETER
được công nhận (dòng đầu tiên trong vòng lặp của quá trình() chỉ in một dòng duy nhất cho 'newReport'
) Làm thế nào tôi có thể kiểm tra các loại chú thích triển khai Auditable? Không có hằng số "ElementKind.TYPE_USE"
để sử dụng. Tôi đã không thể tìm thấy bất kỳ thông tin liên quan về vấn đề này. Cảm ơn đã quan tâm.