[英]What is the purpose of Annotation interface?
每个注释类型都隐式继承java.lang.annotation.Annotation接口。
package java.lang.annotation;
public interface Annotation{
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType();
}
但是注释不会继承Annotation接口中的任何元素,它是所有注释类型的隐式祖先。 因此,如果我在下面执行,将导致编译时错误
@CustomAnnotation(toString="toStringValue")
那么有人可以解释一下
Annotation接口的目的是什么? 以及它究竟用于什么?
Annotation
是一个接口。 那些方法是您的标准接口abstract
方法声明。
在你的例子中你所指的是什么
@CustomAnnotation(toString="toStringValue")
(使用toString
)是一个注释类型元素 。 这是两件不同的事情。 后者是注释类型的特殊语法。 Annotation
不是注释类型,它是接口类型。
Annotation
类型提供的是Annotation
类型的常见超类型。 所以你可以做到
Annotation custom = SomeClass.class.getAnnotation(CustomAnnotation.class);
custom.annotationType();
这些方法( equals
, toString
和hashCode
)只是在Annotation
接口中重新定义,以指定它们的行为。 它们并不是严格要求的,因为Java语言会隐式地将所有这些方法添加到所有接口类型中,如果它们不声明它们的话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.