[go: up one dir, main page]

0% found this document useful (0 votes)
13 views24 pages

Annotations

The document provides an overview of annotations in Java, including their purpose, types, and built-in annotations such as @Override, @SuppressWarnings, and @Deprecated. It explains the structure of custom annotations, including marker, single-value, and multi-value annotations, as well as key annotations like @Target, @Retention, @Inherited, and @Documented. The document also includes code examples demonstrating the usage and implementation of these annotations.

Uploaded by

srinusirisala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views24 pages

Annotations

The document provides an overview of annotations in Java, including their purpose, types, and built-in annotations such as @Override, @SuppressWarnings, and @Deprecated. It explains the structure of custom annotations, including marker, single-value, and multi-value annotations, as well as key annotations like @Target, @Retention, @Inherited, and @Documented. The document also includes code examples demonstrating the usage and implementation of these annotations.

Uploaded by

srinusirisala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Annotations

Annotation: it is a tag that represents the metadata i.e. attached with


class, interface, methods or fields to indicate some additional
information which can be used by java compiler and JVM.
• Annotations in Java are used to provide additional information, so it is
an alternative option for XML and Java marker interfaces.
Note:
• In java java.lang.annotation is a package, which contains the core
classes and interfaces for defining and using annotations in Java.
• Annotation is a Super Type for annotation interfaces in this package.
Hierarchy of Annotations in Java

Note: Annotations do not affect the functionality of the associated method by


themselves. Annotations are metadata that provide information about the
code, but they don’t alter the actual behavior of the method unless they are
processed in some way.
Built-In Annotations(General Purpose Annotations)
@Override
• @Override annotation assures that the subclass method is overriding the parent
class method. If it is not so, compile time error occurs.
• Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better
to mark @Override annotation that provides assurity that method is overridden.

class Animal{ class TestOverrideAnnotation{


void eatSomething(){System.out.println("eating public static void main(String args[]){
something");} Animal a=new Dog();
} a.eatSomething();
}}
class Dog extends Animal{ Output:
@Override TestOverrideAnnotation.java:6: error: method does not
void eatsomething(){System.out.println("eating override or implement a method from a supertype
foods");}//should be eatSomething @Override
} ^
1 error
@SuppressWarnings
• @SuppressWarnings annotation: is used to suppress warnings issued
by the compiler.
import java.util.*;
class TestSupressWarningsAnnotation{
//@SuppressWarnings("unchecked")
/*
public static void main(String args[]){ output with annotation tag
D:\javaprogs>javac
ArrayList list=new ArrayList();
TestSupressWarningsAnnotation.java
list.add("sonoo"); Note: TestSupressWarningsAnnotation.java uses
unchecked or unsafe operations.
list.add("vimal");
Note: Recompile with -Xlint:unchecked for details.
list.add("ratan"); */
for(Object obj:list)
System.out.println(obj);
@Deprecated
This annoation marks that this method is deprecated so compiler prints warning. It informs user that it
may be removed in the future versions. So, it is better not to use such methods.

Note: When using deprecated methods from standard libraries, the compiler automatically issues a warning.
However, for custom or user-defined deprecated methods, you must explicitly mark them with the @Deprecated
annotation; otherwise, the compiler won't provide any warnings.
Ex:
import java.awt.*; /*
class TestDepricated{ D:\javaprogs>javac TestDepricated.java
public static void main(String [] args){ Note: TestDepricated.java uses or overrides a
Frame f=new Frame(); deprecated API.
f.show();// alternative is f.setVisible(); Note: Recompile with -Xlint:deprecation for
details.
}
*/
}
// User defined Deprecated methods
class Employee{
@Deprecated
public void gen_salary(){
System.out.println("BASIC+HRA");
}
public void new_Gen_salary(){
System.out.println("BASIC+DA+HRA");
} Output:
D:\javaprogs>javac TestDepricated.java
}
Note: TestDepricated.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
class TestDepricatedAnnotation{
public static void main(String []args){
Employee e=new Employee();
e.gen_salary();
}}
@FunctionalInterface
A functional interface is an interface that contains exactly one abstract
method.
Using @FunctionalInterface, clearly indicates that the interface is
meant to have only one abstract method. It also makes sure the
compiler enforces this rule by showing an error if there is more than
one abstract method.
.
@FunctionalInterface
interface A {

void x();
void y();// Extra abstract method, sothat compiler gives error
}
class B implements A{
public void x(){System.out.println("hi");}
public void y(){System.out.println("hello");}
}
class FunctionalInterfaceAnnotation{
public static void main(String[] args) { Output:
D:\javaprogs>javac FunctionalInterfaceAnnotation.java
A a=new B();
FunctionalInterfaceAnnotation.java:1: error: Unexpected
a.x(); @FunctionalInterface annotation
a.y(); @FunctionalInterface
} ^
A is not a functional interface
} multiple non-overriding abstract methods found in interface A
1 error
Java Custom Annotations
• @interface element is used to declare an annotation.
Syntax:
public @interface AnnotationName {
DataType elementName() default defaultValue;
}
Here,
•@interface : Keyword used to define an annotation.
•AnnotationName : The name of the custom annotation.
•DataType : The return type of the annotation element (like String, int,
boolean, Class, etc.). It can also be an array of any type (e.g., String[]).
•elementName() : Name of the element (like a method declaration). These are the
values you can pass to the annotation when you use it.
•defaultValue : (Optional) Default value for the annotation element. If no value is
provided by the user when applying the annotation, this default
will be used.
Categories of Annotations:
There are three Categories of annotations.
• Marker Annotation
• Single-Value Annotation
• Multi-Value Annotation
Marker Annotation
• An annotation that has no method, is called marker annotation.
Syntax:
@interface MyAnnotation{}
Ex:
• @Override
• @Deprecated
import java.lang.annotation.Retention; example.display();
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method; // Getting the class object
Class<?> clazz = example.getClass();
// Defining a marker annotation
@Retention(RetentionPolicy.RUNTIME) // Accessing the method by name
@interface TestMarker { try {
Method method = clazz.getMethod("display");
// No elements
}
// Checking if the annotation is present on the method
if (method.isAnnotationPresent(TestMarker.class))
// Applying marker annotation {
public class MarkerAnnotationExample { System.out.println("TestMarker annotation is present.");
} else {
@TestMarker System.out.println("TestMarker annotation is NOT
public void display() { present.");
System.out.println("Marker annotation }
applied!"); } catch (NoSuchMethodException e) {
} System.out.println("Method not found: " +
e.getMessage());
}
public static void main(String[] args) {
}
MarkerAnnotationExample example = new
}
Single-Value Annotation
An annotation that has one method, is called single-value annotation.
Syntax:
@interface MyAnnotation{
int value();
}
• Here we can provide the default value also.
For example:
@interface MyAnnotation{
int value() default 0;
}
import java.lang.annotation.Retention; // Retrieve the Author annotation
import java.lang.annotation.RetentionPolicy; Author authorAnnotation =
import java.lang.reflect.Method; method.getAnnotation(Author.class);

// Define a single-value annotation // Use the annotation value inside the method
@Retention(RetentionPolicy.RUNTIME) if (authorAnnotation != null) {
@interface Author { System.out.println("Feature one implemented by:
" + authorAnnotation.value());
String value(); // Single element
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
public class AuthorInfo {
}
}
@Author("Alice")
public void featureOne() {
public static void main(String[] args) {
// Use reflection to get the annotation value at runtime
AuthorInfo obj = new AuthorInfo();
try {
obj.featureOne();
Method method =
this.getClass().getMethod("featureOne"); }
}
Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For example:
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
We can provide the default value also. For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
How to apply Multi-Value Annotation
Let's see the code to apply the multi-value annotation.
@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")
import java.lang.annotation.Retention; MultiValueExample obj = new MultiValueExample();
import java.lang.annotation.RetentionPolicy; obj.featureOne();
obj.featureTwo();
// Define a multi-value annotation
@Retention(RetentionPolicy.RUNTIME) // Using reflection to access annotation values
@interface DeveloperInfo { try {
String developer(); // One element for developer name // For the featureOne method
String date(); // Another element for development date DeveloperInfo featureOneInfo =
} obj.getClass().getMethod("featureOne").getAnnotation(Devel
operInfo.class);
System.out.println("Feature One - Developer: " +
// Apply the multi-value annotation featureOneInfo.developer() + ", Date: " +
public class MultiValueExample { featureOneInfo.date());

@DeveloperInfo(developer = "Alice", date = "2024-10-21")


public void featureOne() { } catch (NoSuchMethodException e) {
System.out.println("Feature one implementation."); e.printStackTrace();
} }
}
}
public static void main(String[] args) {
Built-in Annotations used in custom annotations in java
• @Target
• @Retention
• @Inherited
• @Documented
@Target
• @Target tag is used to specify at which type, the annotation is used.
• ElementType declares many constants to specify the type of element where annotation is to be applied such as
TYPE, METHOD, FIELD etc.
Element Types Where the annotation can be applied
TYPE class, interface or enumeration
FIELD fields
Note :Without specifying a
METHOD methods @Target, the annotation
CONSTRUCTOR constructors can be used anywhere
LOCAL_VARIABLE local variables
ANNOTATION_TYPE annotation type
PARAMETER parameter
import java.lang.annotation.ElementType; System.out.println("Method with
import java.lang.annotation.Target; MethodOnlyAnnotation");
}
// Define an annotation that can only be applied to
methods // This would cause a compile-time error if
@Target(ElementType.METHOD) uncommented:
@interface MethodOnlyAnnotation { // @MethodOnlyAnnotation("This would cause
an error")
String value();
// private String myField;
}

public static void main(String[] args) {


public class TargetExample {
TargetExample obj = new TargetExample();
obj.myMethod();
@MethodOnlyAnnotation("This annotation is for
methods only") }
public void myMethod() { }
@Retention
@Retention annotation is used to specify to what level annotation will be
available.

RetentionPolicy Availability

refers to the source code, discarded during compilation. It will not be


RetentionPolicy.SOURCE
available in the compiled class.

refers to the .class file, available to java compiler but not to JVM . It is
RetentionPolicy.CLASS
included in the class file.

RetentionPolicy.RUNTIME refers to the runtime, available to java compiler and JVM .


Example to specify the RetentionPolicy
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
Example of custom annotation: creating, }
applying and accessing annotation }
//Creating annotation //Accessing annotation
import java.lang.annotation.*; class TestCustomAnnotation1{
import java.lang.reflect.*; public static void main(String args[])throws Ex
ception{
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) Hello h=new Hello();
@interface MyAnnotation{ Method m=h.getClass().getMethod("sayHello");
int value();
} MyAnnotation manno=m.getAnnotation(MyA
//Applying annotation nnotation.class);
class Hello{ System.out.println("value is: "+manno.value())
;
@MyAnnotation(value=10)
}}
public void sayHello(){
System.out.println("hello annotation");
@Inherited
• @Inherited indicates that an annotation applied to a class is inherited by its subclasses.
• By default, annotations are not inherited by subclasses.
• @Inherited can only be applied to class-level annotations.
import java.lang.annotation.Inherited; public static void main(String[] args) {
import java.lang.annotation.Retention; // Check if SubClass has inherited the annotation
import java.lang.annotation.RetentionPolicy; InheritedAnnotation annotation =
SubClass.class.getAnnotation(InheritedAnnotation.class);
@Inherited if (annotation != null) {
@Retention(RetentionPolicy.RUNTIME) System.out.println("Annotation inherited: " +
@interface InheritedAnnotation { annotation.value());
String value(); } else {
} System.out.println("Annotation not inherited.");
}
// Base class with the annotation }
@InheritedAnnotation("Inherited from BaseClass") }
class BaseClass {
}

// Subclass that inherits the annotation


class SubClass extends BaseClass {
}
@Documented
• @Documented indicates that annotations should be included in the
Javadoc of the annotated element.
• By default, annotations do not appear in the generated
documentation unless marked with @Documented.
import java.lang.annotation.Documented; public void myMethod() {
import java.lang.annotation.Retention; System.out.println("Method in DocumentedExample class");
import java.lang.annotation.RetentionPolicy; }
// Define a documented annotation
@Documented public static void main(String[] args) {
@Retention(RetentionPolicy.RUNTIME) DocumentedExample obj = new DocumentedExample();
@interface DocumentedAnnotation { obj.myMethod();
String description(); }
} }
@DocumentedAnnotation(description = "This class is using a
documented annotation")
public class DocumentedExample {

You might also like