14.07.2013 Views

Contents - Cultural View

Contents - Cultural View

Contents - Cultural View

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Java annotation 168<br />

Java annotation<br />

An annotation, in the Java computer programming language, is a special form of syntactic metadata that can be<br />

added to Java source code. [1] Classes, methods, variables, parameters and packages may be annotated. Unlike<br />

Javadoc tags, Java annotations can be reflective in that they can be embedded in class files generated by the compiler<br />

and may be retained by the Java VM to be made retrievable at run-time. [2]<br />

Examples<br />

// @Twizzle is an annotation to method toggle().<br />

@Twizzle<br />

public void toggle() {<br />

}<br />

// Declares the annotation Twizzle.<br />

public @interface Twizzle {<br />

}<br />

Annotations may include an optional list of key-value pairs:<br />

// Same as: @Edible(value = true)<br />

@Edible(true)<br />

Item item = new Carrot();<br />

public @interface Edible {<br />

}<br />

boolean value() default false;<br />

@Author(first = "Oompah", last = "Loompah")<br />

Book book = new Book();<br />

public @interface Author {<br />

}<br />

String first();<br />

String last();<br />

Annotations themselves may be annotated to indicate where and when they can be used:<br />

@Retention(RetentionPolicy.RUNTIME) // Make this annotation<br />

accessible at runtime via reflection.<br />

@Target({ElementType.METHOD}) // This annotation can only be<br />

applied to class methods.<br />

public @interface Tweezable {<br />

}<br />

The compiler reserves a set of special annotations (including @Deprecated, @Override and<br />

@SuppressWarnings) for syntactic purposes.<br />

Annotations are often used by frameworks as a way of conveniently applying behaviours to user-defined classes and<br />

methods that must otherwise be declared in some external source (such as an XML configuration file) or

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!