Annotations in Java

In this Java article we want to learn about Annotations in Java, Java is popular object oriented programming language that has rich set of features for creating software applications. one feature that can be especially useful for developers is the ability to add annotations to their code. Annotations are a way to provide metadata about code elements, such as classes, methods and fields. in this article we want to talk about basics of annotations in Java and how they can be used in your code.

 

What Are Annotations ?

Annotations are a form of metadata that can be added to code elements in Java. they provide additional information about the code element they are attached to, such as its purpose, behavior or constraints. Annotations can be used by compiler, development tools and runtime environments to provide additional functionality or enforce certain behaviors.

 

Annotations are declared using @ symbol followed by the annotation type name. this is an example of an annotation attached to a class:

In this example @Deprecated annotation is added to MyClass class. this annotation indicates that the class is no longer recommended for use and should be avoided.

 

 

Predefined Annotations

Java comes with a number of predefined annotations that can be used in your code. Here are some of the most common predefined annotations and their uses:

  • @Override: This annotation is used to indicate that a method in subclass is intended to override a method in its superclass.
  • @Deprecated: This annotation is used to indicate that a class, method or field is no longer recommended for use and may be removed in future versions of the API.
  • @SuppressWarnings: This annotation is used to suppress compiler warnings for a given code element.
  • @FunctionalInterface: This annotation is used to indicate that an interface is intended to be functional interface, and it means that it has a single abstract method and can be used with lambda expressions.
  • @Retention: This annotation is used to specify how long an annotation should be retained. possible retention policies are SOURCE, CLASS and RUNTIME.

 

 

Custom Annotations

In addition to predefined annotations, you can also create your own custom annotations in Java. Custom annotations are created using @interface keyword followed by the annotation name. this is an example of a custom annotation that can be used to mark methods as requiring authentication:

In this example @RequiresAuthentication annotation is created with @interface keyword. this annotation has a single attribute, roles which is an array of strings that specifies the roles required for access to the annotated method.

 

 

For using this annotation, you can simply add it to the method you want to annotate like this:

 

 

Learn More

Leave a Comment