Unit:12 Enumerations, autoboxing, and annotations

By Haitomns G


In their simplest form, Java enumerations appear similar to enumerations in other languages. However, this similarity may be only skin deep because, in Java, an enumeration defines a class type. By making enumerations into classes, the capabilities of the enumeration are greatly expanded. For example, in Java, an enumeration can have constructors, methods, and instance variables. Therefore, although enumerations were several years in the making, Java’s rich implementation made them well worth the wait.

Enumeration Fundamentals

An enumeration is created using the enum keyword. For example, here is a simple enumeration that lists various apple varieties:

// An enumeration of apple varieties.

enum Apple {

  Jonathan, GoldenDel, RedDel, Winesap, Cortland }

The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants. Each is implicitly declared as a public, static final member of Apple. Furthermore, their type is the type of the enumeration in which they are declared, which is Apple in this case. Thus, in the language of Java, these constants are called self-typed, in which “self” refers to the enclosing enumeration.

Once you have defined an enumeration, you can create a variable of that type. However, even though enumerations define a class type, you do not instantiate an enum using new. Instead, you declare and use an enumeration variable in much the same way as you do one of the primitive types. For example, this declares ap as a variable of enumeration type Apple:

Apple ap;

Because ap is of type Apple, the only values that it can be assigned (or can contain) are those defined by the enumeration. For example, this assigns ap the value RedDel: ap = Apple.RedDel;

Notice that the symbol RedDel is preceded by Apple.

Two enumeration constants can be compared for equality by using the = = relational operator. For example, this statement compares the value in ap with the GoldenDel constant: if(ap == Apple.GoldenDel) // …

An enumeration value can also be used to control a switch statement. Of course, all  of the case statements must use constants from the same enum as that used by the switch expression. For example, this switch is perfectly valid:

// Use an enum to control a switch statement. switch(ap) {   case Jonathan:     // …

  case Winesap:

    // …

Notice that in the case statements, the names of the enumeration constants are used without being qualified by their enumeration type name. That is, Winesap, not Apple.Winesap, is used. This is because the type of the enumeration in the switch expression has already implicitly specified the enum type of the case constants. There is no need to qualify the constants in the case statements with their enum type name. In fact, attempting to do so  will cause a compilation error.

When an enumeration constant is displayed, such as in a println( ) statement, its name is output. For example, given this statement:

System.out.println(Apple.Winesap); the name Winesap is displayed.

The following program puts together all of the pieces and demonstrates the Apple enumeration:

// An enumeration of apple varieties. enum Apple {

  Jonathan, GoldenDel, RedDel, Winesap, Cortland

class EnumDemo {

  public static void main(String args[])


    Apple ap;

    ap = Apple.RedDel;

    // Output an enum value.

    System.out.println(“Value of ap: ” + ap);


    ap = Apple.GoldenDel;

    // Compare two enum values.     if(ap == Apple.GoldenDel)

      System.out.println(“ap contains GoldenDel.\n”);

    // Use an enum to control a switch statement.     switch(ap) {       case Jonathan:

        System.out.println(“Jonathan is red.”);

        break;       case GoldenDel:

        System.out.println(“Golden Delicious is yellow.”);

        break;       case RedDel:

        System.out.println(“Red Delicious is red.”);

        break;       case Winesap:

        System.out.println(“Winesap is red.”);

        break;       case Cortland:

        System.out.println(“Cortland is red.”);





The output from the program is shown here:

   Value of ap: RedDel

    ap contains GoldenDel.

    Golden Delicious is yellow.

The values( ) and valueOf( ) Methods

All enumerations automatically contain two predefined methods: values( ) and valueOf( ). Their general forms are shown here:

public static enum-type [ ] values( ) public static enum-type valueOf(String str )

The values( ) method returns an array that contains a list of the enumeration constants. The valueOf( ) method returns the enumeration constant whose value corresponds to the string passed in str. In both cases, enum-type is the type of the enumeration. For example, in the case of the Apple enumeration shown earlier, the return type of Apple.valueOf(“Winesap”) is Winesap.

The following program demonstrates the values( ) and valueOf( ) methods:

// Use the built-in enumeration methods.

// An enumeration of apple varieties. enum Apple {

  Jonathan, GoldenDel, RedDel, Winesap, Cortland

class EnumDemo2 {

  public static void main(String args[])


    Apple ap;

    System.out.println(“Here are all Apple constants:”);

    // use values()

    Apple allapples[] = Apple.values();

    for(Apple a : allapples)       System.out.println(a);


    // use valueOf()

    ap = Apple.valueOf(“Winesap”);

    System.out.println(“ap contains ” + ap);



The output from the program is shown here:

    Here are all Apple constants:






    ap contains Winesap

Notice that this program uses a for-each style for loop to cycle through the array of constants obtained by calling values( ). For the sake of illustration, the variable allapples was created and assigned a reference to the enumeration array. However, this step is not necessary because the for could have been written as shown here, eliminating the need for the allapples variable:

for(Apple a : Apple.values())


Now, notice how the value corresponding to the name Winesap was obtained by calling valueOf( ). ap = Apple.valueOf(“Winesap”);

As explained, valueOf( ) returns the enumeration value associated with the name of the constant represented as a string.

Java Enumerations Are Class Types

As explained, a Java enumeration is a class type. Although you don’t instantiate an enum using new, it otherwise has much the same capabilities as other classes. The fact that enum defines a class gives the Java enumeration extraordinary power. For example, you can give them constructors, add instance variables and methods, and even implement interfaces.

It is important to understand that each enumeration constant is an object of its enumeration type. Thus, when you define a constructor for an enum, the constructor is called when each enumeration constant is created. Also, each enumeration constant has its own copy of any instance variables defined by the enumeration. For example, consider the following version of Apple:

// Use an enum constructor, instance variable, and method. enum Apple {

  Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);

  private int price; // price of each apple

  // Constructor

  Apple(int p) { price = p; }

  int getPrice() { return price; }

class EnumDemo3 {

  public static void main(String args[])


    Apple ap;

    // Display price of Winesap.

    System.out.println(“Winesap costs ” +

                       Apple.Winesap.getPrice() +

                       ” cents.\n”);

    // Display all apples and prices.

    System.out.println(“All apple prices:”);

    for(Apple a : Apple.values())

      System.out.println(a + ” costs ” + a.getPrice() +

                         ” cents.”);

  } }

The output is shown here:

   Winesap costs 15 cents.

   All apple prices:

   Jonathan costs 10 cents.

   GoldenDel costs 9 cents.

   RedDel costs 12 cents.

   Winesap costs 15 cents.    Cortland costs 8 cents.

This version of Apple adds three things. The first is the instance variable price, which is used to hold the price of each variety of apple. The second is the Apple constructor, which is passed the price of an apple. The third is the method getPrice( ), which returns the value of price.

When the variable ap is declared in main( ), the constructor for Apple is called once for each constant that is specified. Notice how the arguments to the constructor are specified, by putting them inside parentheses after each constant, as shown here:

Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);

These values are passed to the p parameter of Apple( ), which then assigns this value to price. Again, the constructor is called once for each constant.

Because each enumeration constant has its own copy of price, you can obtain the price of a specified type of apple by calling getPrice( ). For example, in main( ) the price of a Winesap is obtained by the following call:

Apple.Winesap.getPrice( )

The prices of all varieties are obtained by cycling through the enumeration using a for loop. Because there is a copy of price for each enumeration constant, the value associated with one constant is separate and distinct from the value associated with another constant. This is a powerful concept, which is only available when enumerations are implemented as classes, as Java does.

Although the preceding example contains only one constructor, an enum can offer two or more overloaded forms, just as can any other class. For example, this version of Apple provides a default constructor that initializes the price to –1, to indicate that no price data is available:

// Use an enum constructor. enum Apple {

  Jonathan(10), GoldenDel(9), RedDel, Winesap(15), Cortland(8);

  private int price; // price of each apple

  // Constructor

  Apple(int p) { price = p; }

  // Overloaded constructor

  Apple() { price = -1; }

  int getPrice() { return price; } }

Notice that in this version, RedDel is not given an argument. This means that the default constructor is called, and RedDel’s price variable is given the value –1.

Here are two restrictions that apply to enumerations. First, an enumeration can’t inherit another class. Second, an enum cannot be a superclass. This means that an enum can’t be extended. Otherwise, enum acts much like any other class type. The key is to remember that each of the enumeration constants is an object of the class in which it is defined.

Enumerations Inherit Enum

Although you can’t inherit a superclass when declaring an enum, all enumerations automatically inherit one: java.lang.Enum. This class defines several methods that are available for use by all enumerations. The Enum class is described in detail in Part II, but three of its methods warrant a discussion at this time.

You can obtain a value that indicates an enumeration constant’s position in the list of constants. This is called its ordinal value, and it is retrieved by calling the ordinal( ) method, shown here:

final int ordinal( )

It returns the ordinal value of the invoking constant. Ordinal values begin at zero. Thus, in the Apple enumeration, Jonathan has an ordinal value of zero, GoldenDel has an ordinal value of 1, RedDel has an ordinal value of 2, and so on.

You can compare the ordinal value of two constants of the same enumeration by using the compareTo( ) method. It has this general form:

final int compareTo(enum-type e)

Here, enum-type is the type of the enumeration, and e is the constant being compared to  the invoking constant. Remember, both the invoking constant and e must be of the same enumeration. If the invoking constant has an ordinal value less than e’s, then compareTo( ) returns a negative value. If the two ordinal values are the same, then zero is returned. If the invoking constant has an ordinal value greater than e’s, then a positive value is returned.

You can compare for equality an enumeration constant with any other object by using equals( ), which overrides the equals( ) method defined by Object. Although equals( ) can compare an enumeration constant to any other object, those two objects will be equal only if they both refer to the same constant, within the same enumeration. Simply having ordinal values in common will not cause equals( ) to return true if the two constants are from different enumerations.

Remember, you can compare two enumeration references for equality by using = =.

The following program demonstrates the ordinal( ), compareTo( ), and equals( ) methods:

// Demonstrate ordinal(), compareTo(), and equals().

// An enumeration of apple varieties. enum Apple {

  Jonathan, GoldenDel, RedDel, Winesap, Cortland

class EnumDemo4 {

  public static void main(String args[])


    Apple ap, ap2, ap3;

    // Obtain all ordinal values using ordinal().

    System.out.println(“Here are all apple constants” +

                       ” and their ordinal values: “);

    for(Apple a : Apple.values())

      System.out.println(a + ” ” + a.ordinal());

    ap =  Apple.RedDel;     ap2 = Apple.GoldenDel;     ap3 = Apple.RedDel;


    // Demonstrate compareTo() and equals()

    if(ap.compareTo(ap2) < 0)

      System.out.println(ap + ” comes before ” + ap2);

    if(ap.compareTo(ap2) > 0)

      System.out.println(ap2 + ” comes before ” + ap);

    if(ap.compareTo(ap3) == 0)

      System.out.println(ap + ” equals ” + ap3);





      System.out.println(ap + ” equals ” + ap3);

    if(ap == ap3)

      System.out.println(ap + ” == ” + ap3);



The output from the program is shown here:

   Here are all apple constants and their ordinal values:

   Jonathan 0

   GoldenDel 1

   RedDel 2

   Winesap 3

   Cortland 4

   GoldenDel comes before RedDel

   RedDel equals RedDel

   RedDel equals RedDel

   RedDel == RedDel

Type Wrappers

As you know, Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported by the language. Primitive types, rather than objects, are used for these quantities for the sake of performance. Using objects for these values would add an unacceptable overhead to even the simplest of calculations. Thus, the primitive types are not part of the object hierarchy, and they do not inherit Object.

Despite the performance benefit offered by the primitive types, there are times when you will need an object representation. For example, you can’t pass a primitive type by reference to a method. Also, many of the standard data structures implemented by Java operate on objects, which means that you can’t use these data structures to store primitive types. To handle these (and other) situations, Java provides type wrappers, which are classes that encapsulate a primitive type within an object. The type wrapper classes are described  in detail in Part II, but they are introduced here because they relate directly to Java’s autoboxing feature.

The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy. Each is briefly examined next.


Character is a wrapper around a char. The constructor for Character is Character(char ch)

Here, ch specifies the character that will be wrapped by the Character object being created. To obtain the char value contained in a Character object, call charValue( ), shown here: char charValue( )

It returns the encapsulated character.


Boolean is a wrapper around boolean values. It defines these constructors:

Boolean(boolean boolValue)

Boolean(String boolString)

In the first version, boolValue must be either true or false. In the second version, if boolString contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will be false.

To obtain a boolean value from a Boolean object, use booleanValue( ), shown here: boolean booleanValue( )

It returns the boolean equivalent of the invoking object.

The Numeric Type Wrappers

By far, the most commonly used type wrappers are those that represent numeric values. These are Byte, Short, Integer, Long, Float, and Double. All of the numeric type wrappers inherit the abstract class Number. Number declares methods that return the value of an object in each of the different number formats. These methods are shown here:

byte byteValue( ) double doubleValue( ) float floatValue( ) int intValue( ) long longValue( ) short shortValue( )

For example, doubleValue( ) returns the value of an object as a double, floatValue( ) returns the value as a float, and so on. These methods are implemented by each of the numeric type wrappers.

All of the numeric type wrappers define constructors that allow an object to be constructed from a given value, or a string representation of that value. For example, here are the constructors defined for Integer:

Integer(int num)

Integer(String str)

If str does not contain a valid numeric value, then a NumberFormatException is thrown.

All of the type wrappers override toString( ). It returns the human-readable form of the value contained within the wrapper. This allows you to output the value by passing a type wrapper object to println( ), for example, without having to convert it into its primitive type.

The following program demonstrates how to use a numeric type wrapper to encapsulate a value and then extract that value.

// Demonstrate a type wrapper. class Wrap {

  public static void main(String args[]) {

    Integer iOb = new Integer(100);

    int i = iOb.intValue();

    System.out.println(i + ” ” + iOb); // displays 100 100



This program wraps the integer value 100 inside an Integer object called iOb. The program then obtains this value by calling intValue( ) and stores the result in i.

The process of encapsulating a value within an object is called boxing. Thus, in the program, this line boxes the value 100 into an Integer:

Integer iOb = new Integer(100);

The process of extracting a value from a type wrapper is called unboxing. For example, the program unboxes the value in iOb with this statement: int i = iOb.intValue();

The same general procedure used by the preceding program to box and unbox values has been employed since the original version of Java. However, since JDK 5, Java fundamentally improved on this through the addition of autoboxing, described next.


Beginning with JDK 5, Java added two important features: autoboxing and auto-unboxing. Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent type wrapper whenever an object of that type is needed. There is no need to explicitly construct an object. Auto-unboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a type wrapper when its value  is needed. There is no need to call a method such as intValue( ) or doubleValue( ).

The addition of autoboxing and auto-unboxing greatly streamlines the coding of several algorithms, removing the tedium of manually boxing and unboxing values. It also helps prevent errors. Moreover, it is very important to generics, which operate only on objects. Finally, autoboxing makes working with the Collections Framework (described in Part II) much easier.

With autoboxing, it is no longer necessary to manually construct an object in order to wrap a primitive type. You need only assign that value to a type-wrapper reference. Java automatically constructs the object for you. For example, here is the modern way to construct an Integer object that has the value 100:

Integer iOb = 100; // autobox an int

Notice that the object is not explicitly created through the use of new. Java handles this for you, automatically.

To unbox an object, simply assign that object reference to a primitive-type variable. For example, to unbox iOb, you can use this line: int i = iOb; // auto-unbox

Java handles the details for you.

Here is the preceding program rewritten to use autoboxing/unboxing:

// Demonstrate autoboxing/unboxing. class AutoBox {

  public static void main(String args[]) {

    Integer iOb = 100; // autobox an int

    int i = iOb; // auto-unbox

    System.out.println(i + ” ” + iOb);  // displays 100 100



Autoboxing and Methods

In addition to the simple case of assignments, autoboxing automatically occurs whenever a primitive type must be converted into an object; auto-unboxing takes place whenever an object must be converted into a primitive type. Thus, autoboxing/unboxing might occur when an argument is passed to a method, or when a value is returned by a method. For example, consider this:

// Autoboxing/unboxing takes place with // method parameters and return values.

class AutoBox2 {

  // Take an Integer parameter and return

  // an int value;   static int m(Integer v) {     return v ; // auto-unbox to int


  public static void main(String args[]) {

    // Pass an int to m() and assign the return value

    // to an Integer.  Here, the argument 100 is autoboxed

    // into an Integer.  The return value is also autoboxed     // into an Integer.

    Integer iOb = m(100);




This program displays the following result:


In the program, notice that m( ) specifies an Integer parameter and returns an int result. Inside main( ), m( ) is passed the value 100. Because m( ) is expecting an Integer, this value is automatically boxed. Then, m( ) returns the int equivalent of its argument. This causes v to be auto-unboxed. Next, this int value is assigned to iOb in main( ), which causes the int return value to be autoboxed.

Autoboxing/Unboxing Occurs in Expressions

In general, autoboxing and unboxing take place whenever a conversion into an object or from an object is required. This applies to expressions. Within an expression, a numeric object is automatically unboxed. The outcome of the expression is reboxed, if necessary. For example, consider the following program:

// Autoboxing/unboxing occurs inside expressions.

class AutoBox3 {

  public static void main(String args[]) {

    Integer iOb, iOb2;

    int i; 

    iOb = 100;

    System.out.println(“Original value of iOb: ” + iOb);

    // The following automatically unboxes iOb,

    // performs the increment, and then reboxes     // the result back into iOb.


    System.out.println(“After ++iOb: ” + iOb);

    // Here, iOb is unboxed, the expression is

    // evaluated, and the result is reboxed and

    // assigned to iOb2.     iOb2 = iOb + (iOb / 3);

    System.out.println(“iOb2 after expression: ” + iOb2);

    // The same expression is evaluated, but the

    // result is not reboxed.

    i = iOb + (iOb / 3);

    System.out.println(“i after expression: ” + i);

  } }

The output is shown here:

   Original value of iOb: 100

   After ++iOb: 101    iOb2 after expression: 134    i after expression: 134

In the program, pay special attention to this line:


This causes the value in iOb to be incremented. It works like this: iOb is unboxed, the value is incremented, and the result is reboxed.

Auto-unboxing also allows you to mix different types of numeric objects in an expression. Once the values are unboxed, the standard type promotions and conversions are applied. For example, the following program is perfectly valid:

class AutoBox4 {

  public static void main(String args[]) {

    Integer iOb = 100;

    Double dOb = 98.6;

    dOb = dOb + iOb;

    System.out.println(“dOb after expression: ” + dOb);



The output is shown here:    dOb after expression: 198.6

As you can see, both the Double object dOb and the Integer object iOb participated in the addition, and the result was reboxed and stored in dOb.

Because of auto-unboxing, you can use Integer numeric objects to control a switch statement. For example, consider this fragment:

Integer iOb = 2;

 switch(iOb) {

  case 1: System.out.println(“one”);


  case 2: System.out.println(“two”);


  default: System.out.println(“error”); }

When the switch expression is evaluated, iOb is unboxed and its int value is obtained.

As the examples in the program show, because of autoboxing/unboxing, using numeric objects in an expression is both intuitive and easy. In the past, such code would have involved casts and calls to methods such as intValue( ).

Autoboxing/Unboxing Boolean and Character Values

As described earlier, Java also supplies wrappers for boolean and char. These are Boolean and Character. Autoboxing/unboxing applies to these wrappers, too. For example, consider the following program:

// Autoboxing/unboxing a Boolean and Character.

class AutoBox5 {

  public static void main(String args[]) {

    // Autobox/unbox a boolean.

    Boolean b = true;

    // Below, b is auto-unboxed when used in

    // a conditional expression, such as an if.

    if(b) System.out.println(“b is true”);

    // Autobox/unbox a char.

    Character ch = ‘x’; // box a char     char ch2 = ch; // unbox a char

    System.out.println(“ch2 is ” + ch2);

  } }

The output is shown here:

   b is true    ch2 is x

The most important thing to notice about this program is the auto-unboxing of b inside the if conditional expression. As you should recall, the conditional expression that controls an if must evaluate to type boolean. Because of auto-unboxing, the boolean value contained within b is automatically unboxed when the conditional expression is evaluated. Thus, with the advent of autoboxing/unboxing, a Boolean object can be used to control an if statement. Because of auto-unboxing, a Boolean object can now also be used to control any of Java’s loop statements. When a Boolean is used as the conditional expression of a while, for, or do/while, it is automatically unboxed into its boolean equivalent. For example, this is now perfectly valid code:

Boolean b;

// … while(b) { // …

Autoboxing/Unboxing Helps Prevent Errors

In addition to the convenience that it offers, autoboxing/unboxing can also help prevent errors. For example, consider the following program:

// An error produced by manual unboxing. class UnboxingError {

  public static void main(String args[]) {      Integer iOb = 1000; // autobox the value 1000

     int i = iOb.byteValue(); // manually unbox as byte !!!

    System.out.println(i);  // does not display 1000 !

  } }

This program displays not the expected value of 1000, but –24! The reason is that the value inside iOb is manually unboxed by calling byteValue( ), which causes the truncation of the value stored in iOb, which is 1,000. This results in the garbage value of –24 being assigned to i. Auto-unboxing prevents this type of error because the value in iOb will always autounbox into a value compatible with int.

In general, because autoboxing always creates the proper object, and auto-unboxing always produces the proper value, there is no way for the process to produce the wrong type of object or value. In the rare instances where you want a type different than that produced by the automated process, you can still manually box and unbox values. Of course, the benefits of autoboxing/unboxing are lost. In general, new code should employ autoboxing/unboxing. It is the way that modern Java code is written.

Annotations (Metadata)

Since JDK 5, Java has supported a feature that enables you to embed supplemental information into a source file. This information, called an annotation, does not change the actions of a program. Thus, an annotation leaves the semantics of a program unchanged.

However, this information can be used by various tools during both development and deployment. For example, an annotation might be processed by a source-code generator. The term metadata is also used to refer to this feature, but the term annotation is the most descriptive and more commonly used.

Annotation Basics

An annotation is created through a mechanism based on the interface. Let’s begin with an example. Here is the declaration for an annotation called MyAnno:

// A simple annotation type.

@interface MyAnno {

  String str();   int val();


First, notice the @ that precedes the keyword interface. This tells the compiler that an annotation type is being declared. Next, notice the two members str( ) and val( ). All annotations consist solely of method declarations. However, you don’t provide bodies for these methods. Instead, Java implements these methods. Moreover, the methods act much like fields, as you will see.

An annotation cannot include an extends clause. However, all annotation types automatically extend the Annotation interface. Thus, Annotation is a super-interface of all annotations. It is declared within the java.lang.annotation package. It overrides hashCode( ), equals( ), and toString( ), which are defined by Object. It also specifies annotationType( ), which returns a Class object that represents the invoking annotation.

Once you have declared an annotation, you can use it to annotate something. Prior to JDK 8, annotations could be used only on declarations, and that is where we will begin. (JDK 8 adds the ability to annotate type use, and this is described later in this chapter. However, the same basic techniques apply to both kinds of annotations.) Any type of declaration can have an annotation associated with it. For example, classes, methods, fields, parameters, and enum constants can be annotated. Even an annotation can be annotated.

In all cases, the annotation precedes the rest of the declaration.

When you apply an annotation, you give values to its members. For example, here is an example of MyAnno being applied to a method declaration:

// Annotate a method.

@MyAnno(str = “Annotation Example”, val = 100) public static void myMeth() { // …

This annotation is linked with the method myMeth( ). Look closely at the annotation syntax. The name of the annotation, preceded by an @, is followed by a parenthesized list of member initializations. To give a member a value, that member’s name is assigned a value. Therefore, in the example, the string “Annotation Example” is assigned to the str member of MyAnno. Notice that no parentheses follow str in this assignment. When an annotation member is given a value, only its name is used. Thus, annotation members look like fields in this context.

Specifying a Retention Policy

Before exploring annotations further, it is necessary to discuss annotation retention policies.  A retention policy determines at what point an annotation is discarded. Java defines three such policies, which are encapsulated within the java.lang.annotation.RetentionPolicy enumeration. They are SOURCE, CLASS, and RUNTIME.

An annotation with a retention policy of SOURCE is retained only in the source file and is discarded during compilation.

An annotation with a retention policy of CLASS is stored in the .class file during compilation. However, it is not available through the JVM during run time.

An annotation with a retention policy of RUNTIME is stored in the .class file during compilation and is available through the JVM during run time. Thus, RUNTIME retention offers the greatest annotation persistence.

NOTE An annotation on a local variable declaration is not retained in the .class file.

A retention policy is specified for an annotation by using one of Java’s built-in annotations: @Retention. Its general form is shown here: @Retention(retention-policy)

Here, retention-policy must be one of the previously discussed enumeration constants. If no retention policy is specified for an annotation, then the default policy of CLASS is used.

The following version of MyAnno uses @Retention to specify the RUNTIME retention policy. Thus, MyAnno will be available to the JVM during program execution.


@interface MyAnno {

  String str();   int val(); }

Obtaining Annotations at Run Time by Use of Reflection

Although annotations are designed mostly for use by other development or deployment tools, if they specify a retention policy of RUNTIME, then they can be queried at run time by any Java program through the use of reflection. Reflection is the feature that enables information about a class to be obtained at run time. The reflection API is contained in  the java.lang.reflect package. There are a number of ways to use reflection, and we won’t examine them all here. We will, however, walk through a few examples that apply to annotations.

The first step to using reflection is to obtain a Class object that represents the class whose annotations you want to obtain. Class is one of Java’s built-in classes and is defined in java.lang. It is described in detail in Part II. There are various ways to obtain a Class object. One of the easiest is to call getClass( ), which is a method defined by Object. Its general form is shown here:

final Class<?> getClass( )

It returns the Class object that represents the invoking object.

NOTE Notice the <?> that follows Class in the declaration of getClass( ) just shown. This is related to Java’s generics feature. getClass( ) and several other reflection-related methods discussed in this chapter make use of generics. Generics are described in Chapter 14. However, an understanding of generics is not needed to grasp the fundamental principles of reflection.

After you have obtained a Class object, you can use its methods to obtain information about the various items declared by the class, including its annotations. If you want to obtain the annotations associated with a specific item declared within a class, you must first obtain an object that represents that item. For example, Class supplies (among others) the getMethod( ), getField( ), and getConstructor( ) methods, which obtain information about a method, field, and constructor, respectively. These methods return objects of type Method, Field, and Constructor.

To understand the process, let’s work through an example that obtains the annotations associated with a method. To do this, you first obtain a Class object that represents the class, and then call getMethod( ) on that Class object, specifying the name of the method. getMethod( ) has this general form:

Method getMethod(String methName, Class<?> … paramTypes)

The name of the method is passed in methName. If the method has arguments, then Class objects representing those types must also be specified by paramTypes. Notice that paramTypes is a varargs parameter. This means that you can specify as many parameter  types as needed, including zero. getMethod( ) returns a Method object that represents the method. If the method can’t be found, NoSuchMethodException is thrown.

From a Class, Method, Field, or Constructor object, you can obtain a specific annotation associated with that object by calling getAnnotation( ). Its general form is shown here: <A extends Annotation> getAnnotation(Class<A> annoType)

Here, annoType is a Class object that represents the annotation in which you are interested. The method returns a reference to the annotation. Using this reference, you can obtain the values associated with the annotation’s members. The method returns null if the annotation is not found, which will be the case if the annotation does not have RUNTIME retention.

Here is a program that assembles all of the pieces shown earlier and uses reflection to display the annotation associated with a method:

import java.lang.annotation.*; import java.lang.reflect.*;

// An annotation type declaration.


@interface MyAnno {

  String str();   int val();


class Meta {

  // Annotate a method.

  @MyAnno(str = “Annotation Example”, val = 100)

  public static void myMeth() {

    Meta ob = new Meta();

    // Obtain the annotation for this method

    // and display the values of the members.     try {       // First, get a Class object that represents       // this class.

      Class<?> c = ob.getClass();

      // Now, get a Method object that represents       // this method.

      Method m = c.getMethod(“myMeth”);

      // Next, get the annotation for this class.

      MyAnno anno = m.getAnnotation(MyAnno.class);

      // Finally, display the values.

      System.out.println(anno.str() + ” ” + anno.val());

    } catch (NoSuchMethodException exc) {

      System.out.println(“Method Not Found.”);



  public static void main(String args[]) {


  } }

The output from the program is shown here:

   Annotation Example 100

This program uses reflection as described to obtain and display the values of str and val in the MyAnno annotation associated with myMeth( ) in the Meta class. There are two things to pay special attention to. First, in this line

MyAnno anno = m.getAnnotation(MyAnno.class);

notice the expression MyAnno.class. This expression evaluates to a Class object of type MyAnno, the annotation. This construct is called a class literal. You can use this type of expression whenever a Class object of a known class is needed. For example, this statement could have been used to obtain the Class object for Meta:

Class<?> c = Meta.class;

Of course, this approach only works when you know the class name of an object in advance, which might not always be the case. In general, you can obtain a class literal for classes, interfaces, primitive types, and arrays. (Remember, the <?> syntax relates to Java’s generics feature. It is described in Chapter 14.)

The second point of interest is the way the values associated with str and val are obtained when they are output by the following line:

System.out.println(anno.str() + ” ” + anno.val());

Notice that they are invoked using the method-call syntax. This same approach is used whenever the value of an annotation member is required.

Also, Read

  1. Unit-6 Introducing Classes
  2. Unit: 7 A Closer Look at Methods and Classes
  3. Unit: 8 Inheritance
  4. Unit: 9 Packages and Interface
  5. Unit: 10 Exception Handling
  6. Unit-11 Multithreaded Programming

Haitomns G. is a desktop, android, and web developer based in Nepal. He has worked on building several websites, apps, and softwares for clients and independent projects. He is experienced in C, C++, C#, Java, Python, SQL, HTML, CSS, PHP, and JavaScript.

1 thought on “Unit:12 Enumerations, autoboxing, and annotations”

  1. I have learn a few just right stuff here. Certainly worth bookmarking for revisiting. I surprise how so much effort you put to make the sort of wonderful informative site.


Leave a Comment

Slide to prove you're not a bot/spammer *