×

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version.

In general, configurations can be done either by XML or by annotations.

Hibernate and spring framework users prefer annotations rather than XML and Java marker interface.

The powerful annotations made the configuration easier.

The special character @ is used to represent an annotation.

Annotations will guide the compiler on how to treat a method/class and in associating the data, and has nothing to do at runtime.

Annotations are available in Java.lang.annotation.Annotations which composed of both standard and inbuilt annotations.

@Autowired, @Override, @Deprecated, and @SuppressWarnings are some of the general-purpose annotations.

Types of Annotations:

Annotations are broadly classified into five types.

Marker Annotations-These is used just for declaration, and these annotations do not contain any data. Example Includes @Override

Single value Annotations- This has a value specified along with the Annotation.

Example-- @Annotation(“value”)

Full Annotations- They contain numerous data members.

Example- @Annotation(key=”name”, value=”test”)

Type Annotations- This can be used anywhere. These are declared with @Target Annotation.

Example- @Target(Test. name)

Repeating Annotations- These can be annotated to apply more than once. For example, to repeat, @Repeatable can be used. Mostly the value fields will be an array.

Example-@Repeatable(test.class)

Below described are Some annotations which are predefined and often used.

@Deprecated- A marker annotation indicates a declaration is replaced by the latest version.

@ Deprecated tag is for the runtime reflection, which has a high preference than @Deprecated Annotation.

Test.java:

public class Test{  
  @Deprecated   
 public void Display()   
 {       
 System.out.println("test display()");   
 }    
 public static void main(String args[])    {    
    test d1 = new test();      
  d1.Display();  
  }
}

Output:

How annotations work in Java

@SuppressWarning This Annotation is used to tell the compiler to suppress a specified compiler warning. @Suppresswarning can be used with a name in string format to suppress. Any unchecked or deprecated warnings are generated.

Test.java:

class Test
{
    @Deprecated
    public void Display()
    {
        System.out.println("test display()");
    }
}
 public class SuppressWarning
{
    // If we comment below Annotation, the program generates
    // warning
    @SuppressWarnings({"test", "check"})
    public static void main(String args[])
    {
     Test d1 = new Test();
        d1.Display();
    }
}

Output:

How annotations work in Java

@Documented

It tells that Annotation should be documented. The @Document will help tools such as JavaDoc to process the Annotation and inform in the generated document.

@Target It can be used to use one Annotation in another annotation. The @Target has an argument dedicated to constant elementType enumeration. This specifies the declaration to be applied for the Annotation.

Examples of some of the target annotations

Constant                           Annotation where it is applicable to

ANNOTATION_TYPE   for other annotation

FIELD                             for fields

METHOD                        for referring to a method

….

@Inheritted is considered as a marker annotation which can be applied to annotation declaration.

@Inherited Annotation will help a subclass to inherit a super class. This helps when an annotation is not present in the subclass, then it tells to check the superclass.

@Override is used to specify that we are overriding a method.

How does @Override work?

Let's have a look at an example...

consider a class with some methods, extends another class, and the extended class should override a method when it is called the @override method is used to ensure that the correct method is over-ridden and else it will return a compilation error in case no method is found to override.

Sample.java

class A{
public void printMeIfCalled(){
System.out.println("I am in A class");
}
}
class B extends A{
public void printMeifcalled(){
System.out.println("I am in B class");
}
}
public class Sample{
public static void main (String[] args){
B call= new B();
call.printMeIfCalled();
}
}

Output:

How annotations work in Java

Here the output will be "I am in A class" because the methods are different in both classes. So, overriding is not possible.

If we use @Override in class B for printMeifcalled(), it will throw a compilation error because there is no method to override in class A.

class A{
public void printMeIfCalled(){
System.out.println("I am in A class");
}
}
class B extends A{
@Override
public void printMeifcalled(){  //here, the compilation error will be thrown because the name cannot be overridden and can be corrected.
System.out.println("I am in B class");
}
}
public class sample{
public static void main(String[] args){
B call= new B();
call.printMeIfCalled();
}
}

Let's look at some of the custom or secondary, or user-defined annotations.

It is very rare that an annotation is defined and used. Custom annotations are used to annotate the basic elements such as variables, and methods. This Annotation can be used before declaring an element.

public @interface<Testannotation>
{         
  String <test>() “testing annotation”;
}

Related Topics

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.