注释界面的目的是什么?

时间:2017-01-26 18:49:52

标签: java annotations

每个注释类型都隐式继承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接口的目的是什么?以及究竟是什么   是用吗?

1 个答案:

答案 0 :(得分:3)

Annotation是一个界面。这些方法是您的标准接口abstract方法声明。

你在

的例子中指的是什么
@CustomAnnotation(toString="toStringValue")

(使用toString)是annotation type element。这是两件不同的事情。后者是注释类型的特殊语法。 Annotation不是注释类型,它是一种接口类型。

Annotation类型提供的是注释类型的常见超类型。所以你可以做到

Annotation custom = SomeClass.class.getAnnotation(CustomAnnotation.class);
custom.annotationType();

这些方法(equalstoStringhashCode)只是在Annotation界面中重新定义,以指定其行为。它们并不是严格要求的,因为如果Java语言没有声明它们,则隐式adds all those methods to all interface types

相关问题