Trong khi câu trả lời cho những câu hỏi như hỏi là Java Method.getAnnotation()
không xem xét phương pháp ghi đè, đôi khi nó là hữu ích để tìm các chú thích này. Dưới đây là một phiên bản hoàn chỉnh hơn về câu trả lời Saintali rằng Tôi hiện đang sử dụng:
public static <A extends Annotation> A getInheritedAnnotation(
Class<A> annotationClass, AnnotatedElement element)
{
A annotation = element.getAnnotation(annotationClass);
if (annotation == null && element instanceof Method)
annotation = getOverriddenAnnotation(annotationClass, (Method) element);
return annotation;
}
private static <A extends Annotation> A getOverriddenAnnotation(
Class<A> annotationClass, Method method)
{
final Class<?> methodClass = method.getDeclaringClass();
final String name = method.getName();
final Class<?>[] params = method.getParameterTypes();
// prioritize all superclasses over all interfaces
final Class<?> superclass = methodClass.getSuperclass();
if (superclass != null)
{
final A annotation =
getOverriddenAnnotationFrom(annotationClass, superclass, name, params);
if (annotation != null)
return annotation;
}
// depth-first search over interface hierarchy
for (final Class<?> intf : methodClass.getInterfaces())
{
final A annotation =
getOverriddenAnnotationFrom(annotationClass, intf, name, params);
if (annotation != null)
return annotation;
}
return null;
}
private static <A extends Annotation> A getOverriddenAnnotationFrom(
Class<A> annotationClass, Class<?> searchClass, String name, Class<?>[] params)
{
try
{
final Method method = searchClass.getMethod(name, params);
final A annotation = method.getAnnotation(annotationClass);
if (annotation != null)
return annotation;
return getOverriddenAnnotation(annotationClass, method);
}
catch (final NoSuchMethodException e)
{
return null;
}
}
Nguồn
2013-06-24 17:08:49
Ngoài ra, trutheality, * Tôi * đã tìm kiếm trước khi tôi hỏi, và tôi đã đưa ra trang này. Xin chúc mừng, bạn hiện là một phần của những kết quả tìm kiếm đó. Đó là lý do tại sao trang web này là ở đây. :) Ngoài ra, câu trả lời của bạn ngắn gọn hơn nhiều so với việc xem xét tài liệu đó. – Tustin2121
Một câu hỏi để tiếp tục điều này ... nếu một khung tìm phương thức dựa trên chú thích và sau đó gọi nó, phiên bản nào của phương thức được gọi? Phương thức của lớp con nên ghi đè phụ huynh nhưng nó được tôn trọng với lời gọi phản xạ? –