75% developed

Custom Annotations

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Navigate Javadoc & Annotations topic: v  d  e )


Annotations can be viewed as a source of defining meta-data for a piece of code in Java. The annotation @CodeDescription used in the following sections does not come as a part of the Java API.

Annotation Type Declaration[edit | edit source]

Before you can use an annotation with classes, theirs members and statements or expressions, you need to define an annotation type. Following is the syntax on how to define a type for the mentioned annotation.

Computer code Code listing 1.1: Annotation type declaration
@interface CodeDescription
{
    String author();
    String version();
}

That's it! Our first ever annotation has been defined. Now, we can use it with any of our classes. An annotation definition if you look closely resembles the definition of a normal interface, except that the interface keyword is preceded by the @ character. Some refer to this syntactical declaration as the annotation type declaration due to the fact that @ is 'AT' or 'Annotation Type' for that very instance.

Annotation Element Declarations[edit | edit source]

What look like methods in the body of the annotation definition are called annotation element declarations. These are the named entities that we used with the annotation body in the example in the previous section. However, for the sake of clarity, code below also represents the calling of the following annotation:

Computer code Code listing 1.2: Calling of annotation
public class MyMethod
{
    @CodeDescription
    (
        author = "Unknown",
        version = "1.0.0.1"
    )
    public void doSomething()
    {
        ...
    }
}

Note:
Instead of using the declaration with the class, the annotation is used with the method doSomething(). This might not demonstrate the power of annotations yet, but more will be explored in later chapters.

Using a default value[edit | edit source]

Now, for instance, you want the annotation to know that if no value for the version element is present, then it should use a default value. Declaring a default value would be done the following way.

Computer code Code listing 1.3: Using default values.
@interface CodeDescription
{
    String author();
    String version() default "1.0.0.1";
}

So, now if you use the same code again, you can ignore the version element because you know that the value is to be provided by default.

Computer code Code listing 1.4: Pre-defined value.
public class MyMethod
{
    @CodeDescription(author = "Sysop")
    public void doSomething()
    {
        ...
    }
}


Clipboard

To do:
Add some exercises like the ones in Variables