java - 为什么 Java 8 的注解类型中不允许使用默认方法?

标签 java interface annotations java-8

今天看到了注解的精彩世界,于是尝试了自己的代码,但是编译不通过:

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 an ElementValue (§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 以来 interfacedefault 方法的语法。您可以在此方法中执行任何操作。 对于仅提供元数据而不提供行为的注解而言,情况并非如此。

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/

相关文章:

java - 我正在尝试编写代码,但面临 java.lang.StringIndexOutOfBoundsException。请检查代码

java - 在 FragmentActivity 中初始化接口(interface)

java - 这段代码中的 T 是类还是接口(interface)?

java - 获取注释值?

javascript - JSDoc:注释导出的方法

java - AWS S3 Java SDK - 拒绝访问

java - 在没有注释的情况下强制对 Spring MVC Controller 的 JSON 主体中的字符串值进行全局验证

从 jar 中执行类文件时出现 java.lang.ClassNotFoundException

java - 具有所有抽象方法的抽象类和接口(interface)之间有什么区别(不是技术上的)

xml - 在 Spring 3 中使用注解注册转换器和 converterFactories