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?
As we know, an interface can't have a state, and therefore, the default method can't access the state.
Interfaces can have default methods with implementation in Java 8 on later. Interfaces can have static methods as well, similar to static methods in classes. Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.
An annotation is a construct associated with Java source code elements such as classes, methods, and variables.
A default method cannot override a method from java.
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 anElementValue
(§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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With