今天看到了注解的精彩世界,于是尝试了自己的代码,但是编译不通过:
public @interface SomeAnnotation {
public String sayHello1() default "Hello world";
default public String sayHello2() {
return "Hello world";
}
}
您在 sayHello1
中看到的是如何指定注释的默认参数。
不过,我想知道的是为什么 sayHello2
是不允许的,它自 Java 8 起可用。
对我来说,它似乎提供了相同的功能,或者我在这里遗漏了什么?
另外,为什么自 Java 5 以来注解可以访问默认方法体(尽管非常简单),而接口(interface)必须等到 Java 8?
最佳答案
这个
public String sayHello1() default "Hello world";
提供注释元素的默认值。也就是说,如果您没有在注释中提供它,那就是它应该具有的值。 From the JLS
The body of an annotation type may contain method declarations, each of which defines an element of the annotation type. An annotation type has no elements other than those defined by the methods it explicitly declares.
和
An annotation type element may have a default value, specified by following the element's (empty) parameter list with the keyword
default
and anElementValue
(§9.7.1).
所以
@SomeAnnotation // sayHello1 would have value "Hello world"
public class Foo {}
和
@SomeAnnotation(sayHello1 = "other value") // sayHello1 would have value "other value"
public class Foo {}
然后
SomeAnnotation ann = ...;
String value = ann.sayHello1();
如果您不提供默认
值,那么您必须在注释某些内容时提供一个值。
这个
default public String sayHello2() {
return "Hello world";
}
是自 Java 8 以来 interface
中 default
方法的语法。您可以在此方法中执行任何操作。 对于仅提供元数据而不提供行为的注解而言,情况并非如此。
Also, why did annotations have access to default method bodies (albeit very simple ones) since Java 5, while interfaces had to wait until Java 8?
他们没有。上面两件事是完全不同的。
关于java - 为什么 Java 8 的注解类型中不允许使用默认方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23200646/