Overview
- What are Annotations?
- Use of Annotations
- Annotations Placements
- Built in Java Annotations
- Custom Annotations
What Are Annotations?
- Metadata about the java code.
- Introduced from Java 5
- Mostly do not effect the code execution, sometimes they might.
- E.g. @Override
- Use of @ points to the compiler that it is an annotation.
Use of Annotations
- Compilers can use them for suppressing warnings and detecting errors.
- Software tools can gather information from them and generate code, XML information etc.
- These annotations could also be modified so that they are available at runtime as well.
Annotations Placements
- Annotations could be placed before java packages, types, constructors, methods, fields, parameters, and local variables.
- The annotation can contain multiple elements like @Entity(tableName = “vehicles”, primaryKey = “id”)
- In case there is a single element, convention is to call that element “value” e.g. @Entity(value=“entity”)
- It can also be left as blank when there is just a single element like @Entity(“entity”)
Annotations are defined using the @ symbol followed by an annotation type, and they can also include elements with values.
Built In Java Annotations
- @Deprecated:- This annotation is used to mark a class, method or field as deprecated, meaning it should no longer be used.
- @Override:- The @Override Java annotation is used above methods that override methods in a superclass. If the method does not match a method in the superclass, the compiler will give you an error.
- @SuppressWarnings:- The @SuppressWarnings annotation makes the compiler suppress warnings for a given method.
- Demo
Custom Annotations
- An annotation type is a Java interface, except that you must add an ‘@’ sign before the interface keyword when declaring it.
- It can be created like.
public @interface CustomAnnotation
{
String value();
Integer id();
}
- Element default values can be specified.
Custom Annotations (Continued…)
- @Retention:- Used to specify if the custom annotation is available at runtime.
- @Target:- Used to specify with which java element the annotation could be used..
- @Inherited:- Used to specify that custom annotation used with parent class gets inherited by subclasses as well.
- @Documented:- Used to specify that custom annotation should be read and used by JavaDoc tool.