Pregunta

I today saw a glimpse of the wonderful world of annotations, so I tried my own code, but it does not want to compile:

public @interface SomeAnnotation {
    public String sayHello1() default "Hello world";

    default public String sayHello2() {
        return "Hello world";
    }
}

What you see in sayHello1, is how default arguments for annotations are to be specified.
What I am wondering though, is why sayHello2 is not allowed, which is available since Java 8.

To me it seems to be providing the same functionality, or am I missing something here?

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?

¿Fue útil?

Solución

This

public String sayHello1() default "Hello world";

is providing the default value of the annotation element. That is, if you didn't provide it in the annotation, that's the value it would have. 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.

and

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).

So

@SomeAnnotation // sayHello1 would have value "Hello world"
public class Foo {}

and

@SomeAnnotation(sayHello1 = "other value") // sayHello1 would have value "other value"
public class Foo {}

Then

SomeAnnotation ann = ...;
String value = ann.sayHello1();

If you don't provide a default value, then you must provide a value when annotating something.

This

default public String sayHello2() {
    return "Hello world";
}

is the syntax for a default method in an interface since Java 8. You can execute anything in this method. That is not true for an annotation which only provides metadata, not behavior.

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?

They didn't. The two things above are completely different.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top