Java annotation: Difference between revisions

Content deleted Content added
FFEFD5 (talk | contribs)
Switch to gender neutral language
Tags: Mobile edit Mobile app edit iOS app edit
Line 243:
When Java source code is compiled, annotations can be processed by compiler plug-ins called annotation processors. Processors can produce informational messages or create additional Java source files or resources, which in turn may be compiled and processed. However, annotation processors cannot modify the annotated code itself. (Code modifications may be implemented using methods beyond the Java Language Specification.) The Java compiler conditionally stores annotation metadata in the class files, if the annotation has a <code>RetentionPolicy</code> of <code>CLASS</code> or <code>RUNTIME</code>. Later, the [[Java virtual machine|JVM]] or other programs can look for the metadata to determine how to interact with the program elements or change their behavior.
 
In addition to processing an annotation using an annotation processor, a Java programmer can write histheir own code that uses reflections to process the annotation. [[Java Platform, Standard Edition|Java SE]] 5 supports a new interface that is defined in the <code>java.lang.reflect</code> package. This package contains the interface called <code>AnnotatedElement</code> that is implemented by the Java reflection classes including <code>Class</code>, <code>Constructor</code>, <code>Field</code>, <code>Method</code>, and <code>Package</code>. The implementations of this interface are used to represent an annotated element of the program currently running in the Java Virtual Machine. This interface allows annotations to be read reflectively.
 
The <code>AnnotatedElement</code> interface provides access to annotations having <code>RUNTIME</code> retention. This access is provided by the <code>getAnnotation</code>, <code>getAnnotations</code>, and <code>isAnnotationPresent</code> methods. Because annotation types are compiled and stored in byte code files just like classes, the annotations returned by these methods can be queried just like any regular Java object. A complete example of processing an annotation is provided below: