Академический Документы
Профессиональный Документы
Культура Документы
Annotations
Unlike Javadoc tags, Java annotations are reflective in that they are
embedded in class files generated by the compiler and may be
retained by the Java VM to be made retrievable at run-time.
Some developers think that the Java compiler understands the tag
and work accordingly. This is not right.
For example there is a override annotation that lets you specify that a
method overrides another method from a superclass. At this, the Java
compiler will ensure that the behavior you indicate in your metadata
actually happens at a code level as well.
Marker annotations
There annotations have no variables. These are identified by name,
with no additional data supplied. For example:
Code:
@SingleValueAnnotation
Single-value annotations
These are similar to markers, but also provide a single piece of data.
You can only provide a single bit of data with these. For example:
Code:
@SingleValueAnnotation(”my data”)
Full annotations
There have multiple data members. Annotations of this type won’t
look quite so much like a normal Java method:
Example :
There are two things you need to consider with annotations. One is
the “annotation” itself; another is the “annotation type.”
An annotation is the meta-tag that you will use in your code to give it
some life.
Marker
Single-Element
Full-value or multi-value
Usage:
@MyAnnotation
public void mymethod() { .... }
Usage:
@MyAnnotation ("What to do")
public void mymethod() { .... }
Usage:
@MyAnnotation (doSomething="What to do", count=1, date="09-09-
2005")
public void mymethod() { .... }
– Target
– Retention
– Documented
– Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Test_Retention {
String doTestRetention();
}
Example 7
First, define your annotation:
@Inherited public @interface myParentObject {
boolean isInherited() default true;
String doSomething() default "Do what?";
}
As you can see, you do not have to define the interface methods
inside the implementing class. These are automatically inherited
because of using the @Inherited tag.