By Shubham Aggarwal | 1/16/2017 | General |Intermediate

Annotations in Java

Annotations in Java

This article introduces you to Annotations in Java, how they are made, of what use they are and what purpose do they actually achieve. We characterised annotations based on their syntax.

Annotations

Lambda expressions are by far the most discussed and promoted feature of the Java 8 release. While I agree that Lambdas are a large improvement towards functional programming, I think that there are other Java 8 features that come short because of the Lambda hype. In this post we will see a number of examples from another excellent Java 8 feature: Type Annotations.

 

Before the Java 8 release, annotations could only be applied to declarations. As of the latest Java 8 release, annotations can also be applied to any type use. This means that annotations can be used anywhere you used to use a type.

 

>>> For a definition, annotations are a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Uses of Annotations

Annotations have a number of uses, among them are:

 

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings or have additional information.
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.

 

Basics

In its simplest form, an annotation looks like the following:

 

@Entity

 

The at sign character (@) indicates to the compiler that what follows is an annotation. In the following example, the annotation name is Override:

 

 

@Override
int myOverridenMethod() { ... }

The annotation can include elements, which can be named or unnamed, and there can be values for those elements:

 

 

@Editor(
  name = "Shubham Aggarwal",
  date = "5/20/1994"
)

class MyClass() { ... }

Or

 

 

@SuppressWarnings(value = "unchecked")
void myAnnotatedMethod() { ... }

If there is just one element named value, then the name can be omitted, as in:

 

 

@SuppressWarnings("unchecked")
void myAnnotatedMethod() { ... }

If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example.

Repeating Annotations

It is also possible to use multiple annotations on the same declaration:

 

 

@Editor(name = "Shubham Aggarwal")
@MyMusic
class MyClass { ... }

If the annotations have the same type, then this is called a repeating annotation:

@Editor(name = "Shubham Aggarwal")
@Editor(name = "DiscoverSDK")
class MyClass { ... }

 

Use of Annotations

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.

 

As of Java 8, annotations can also be applied to the use of types.

Here are some examples:

  • Class instance creation expression:

 

new @Interned MyObject();

 

  • Type cast:

 

myString = (@NonNull String) str;

 

  • implements clause:

 

 

class UnmodifiableList<T> implements
  @Readonly List<@Readonly T> { ... }
  • Thrown exception declaration:

 

 

void monitorTemperature() throws

       @Critical TemperatureException { ... }

This form of annotation is called a type annotation.

Predefined Annotation Types

There are pre-defined annotations in Java 8. Some annotations are used by the Javac compiler and some apply to other annotations.

 

Let’s look at few examples with the sample code snippet:

 

  • @Deprecated

 

@Deprecated annotation specifies that the marked element is deprecated and should no longer be used because it’s newer version is available.

 

When an element is deprecated, it should also be documented using the Javadoc @deprecated tag, as shown in the following example. Example code snippet should look like this:

 

 

// Javadoc comment follows

   /**
    * @deprecated
    * explain why it was deprecated
    */

   @Deprecated
   static void myDeprecatedMethod() { }
}
  • @Override

 

@Override annotation specifies the compiler that the element is meant to override an element declared in a superclass. Overriding methods is discussed in Oracle’s Interfaces and Inheritance article.

 

 

  // mark method as a superclass method
  // that has been overridden
  @Override
  int overriddenMethod() { }

 

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler will generate an error.

 

  • @SuppressWarnings

 

@SuppressWarnings annotation specifies the compiler to suppress specific warnings that it would otherwise generate. In the following example, a deprecated method is used, and the compiler usually generates a warning. In this case, however, the annotation causes the warning to be suppressed or to be avoided.

 

 

  // use a deprecated method and tell
  // compiler not to generate a warning

  @SuppressWarnings("deprecation")
   void useDeprecatedMethod() {
       // deprecation warning
       // - suppressed
       objectOne.deprecatedMethod();
   }

Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked. The unchecked warning can occur when interfacing with legacy code written before the advent of generics. To suppress multiple categories of warnings, use the following code snippet as sample:

 

@SuppressWarnings({"unchecked", "deprecation"})

 

  • @SafeVarargs

 

This annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.

 

  • @FunctionalInterface

 

This annotation, introduced in Java SE 8, specifies that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

Annotations That Apply to Other Annotations

Annotations that apply to other annotations are called meta-annotations. Examples are:

  • @Retention

 

This annotation specifies how the marked annotation is stored:

  • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
  • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
  • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.

 

  • @Documented

 

This annotation specifies that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.)

 

  • @Target

 

This annotation specifies another annotation to restrict what kind of Java elements the annotation can be applied to. A target annotation specifies one of the following element types as its value:

  • ElementType.ANNOTATION_TYPE can be applied to an annotation type.
  • ElementType.CONSTRUCTOR can be applied to a constructor.
  • ElementType.FIELD can be applied to a field or property.
  • ElementType.LOCAL_VARIABLE can be applied to a local variable.
  • ElementType.METHOD can be applied to a method-level annotation.
  • ElementType.PACKAGE can be applied to a package declaration.
  • ElementType.PARAMETER can be applied to the parameters of a method.
  • ElementType.TYPE can be applied to any element of a class.

 

  • @Inherited

 

This annotation indicates that the annotation type can be inherited from the superclass. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This annotation applies only to class declarations.

 

  • @Repeatable

 

This annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use.

Conclusion

I hope this guide was helpful to you and you enjoyed reading it.

 

Type annotations are an interesting addition to the Java type system. They can be applied to any use of a type and enable a more detailed code analysis. We explored many Annotations pre-defined in Java programming language and how can we define our own.

By Shubham Aggarwal | 1/16/2017 | General

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
3220
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
User photo
3060
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now