×

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

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 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.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.