25
Đây là một lớp thử nghiệm:Java: không thể truy cập vào các chú thích thông qua phản ánh
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class TestAnnotations {
@interface Annotate{}
@Annotate public void myMethod(){}
public static void main(String[] args) {
try{
Method[] methods = TestAnnotations.class.getDeclaredMethods();
Method m = methods[1];
assert m.getName().equals("myMethod");
System.out.println("method inspected ? " + m.getName());
Annotation a = m.getAnnotation(Annotate.class);
System.out.println("annotation ? " + a);
System.out.println("annotations length ? "
+ m.getDeclaredAnnotations().length);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Dưới đây là kết quả của tôi:
method inspected ? myMethod
annotation : null
annotations length : 0
Những gì tôi đang thiếu để làm cho các chú thích có thể nhìn thấy thông qua sự phản ánh?
Tôi có cần bộ xử lý chú thích ngay cả khi chỉ kiểm tra sự hiện diện của chúng?
Cảm ơn một nhóm! – glmxndr
Tôi có thể hỏi, nếu bạn tình cờ biết liệu có cách nào để thay đổi hành vi mặc định của chính sách lưu giữ CLASS thành RUNTIME không? – glmxndr
Theo như tôi biết điều đó là không thể, nhưng tôi có thể sai. – abyx