Creating a custom annotation in Java involves several steps. Here's how you can create and use a custom annotation:
1. Define the Custom Annotation
You define a custom annotation using the @interface keyword. Annotations can have elements, which are essentially methods without bodies that can return values like primitives, String, Class, enum, or arrays of these types.
Example: Defining a Custom Annotation
java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) // Specifies that the annotation is available at runtime
@Target(ElementType.METHOD) // Specifies that this annotation can be applied to methods
public @interface MyCustomAnnotation {
String value() default "Default Value"; // Element with a default value
int count() default 1; // Another element with a default value
}
2. Apply the Custom Annotation
Once you've defined your custom annotation, you can apply it to classes, methods, fields, etc., depending on the @Target you specified.
Example: Using the Custom Annotation
java
public class MyClass {
@MyCustomAnnotation(value = "Hello, World!", count = 5)
public void myMethod() {
System.out.println("This is my method.");
}
}
3. Access the Annotation via Reflection
To use the annotation information at runtime, you typically access it via Java Reflection.
Example: Accessing the Annotation Information
java
import java.lang.reflect.Method;
public class AnnotationExample {
public static void main(String[] args) {
try {
// Get the MyClass class object
Class<MyClass> obj = MyClass.class;
// Loop through all methods of MyClass
for (Method method : obj.getDeclaredMethods()) {
// Check if the method has the MyCustomAnnotation
if (method.isAnnotationPresent(MyCustomAnnotation.class)) {
// Get the annotation instance
MyCustomAnnotation annotation = method.getAnnotation(MyCustomAnnotation.class);
// Access the elements of the annotation
System.out.println("Method Name: " + method.getName());
System.out.println("Annotation Value: " + annotation.value());
System.out.println("Annotation Count: " + annotation.count());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. Run the Example
When you run the AnnotationExample class, it will access the annotation on myMethod in MyClass and print the values of the annotation elements.
Output:
Out put
Method Name: myMethod
Annotation Value: Hello, World!
Annotation Count: 5
Explanation of Annotations
- @Retention:
Specifies how long annotations with the annotated type are to be retained.
RetentionPolicy.RUNTIME means the annotation is available at runtime.
- @Target:
Specifies the kinds of program elements to which an annotation type is
applicable. ElementType.METHOD indicates that the annotation can be
applied to methods.
- @interface:
Used to declare an annotation type.
Summary
- Define
the Annotation: Use @interface to create the annotation with optional
elements.
- Apply
the Annotation: Annotate methods, classes, or other elements using the
custom annotation.
- Access
the Annotation: Use reflection to inspect and use the annotation data
at runtime.
Approach 2
Certainly! Here's a different way to create and use a custom annotation in Java. This time, we'll create an annotation that can be applied to both methods and fields, and we'll include an enum element to demonstrate another aspect of annotations.
1. Define the Custom Annotation using ENUM
This annotation will include an enum element, a String element, and a boolean element. It will be applicable to both fields and methods.
java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Define an enum to be used as an annotation element
enum Priority {
LOW, MEDIUM, HIGH
}
// Define the custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD}) // Applicable to both methods and fields
public @interface TaskInfo {
String author() default "Unknown";
Priority priority() default Priority.MEDIUM;
boolean completed() default false;
}
2. Apply the Custom Annotation
Now, let's use the @TaskInfo annotation in a class to annotate both a method and a field.
java
public class Task {
@TaskInfo(author = "John Doe", priority = Priority.HIGH, completed = true)
private String taskName;
@TaskInfo(author = "Jane Doe", priority = Priority.LOW, completed = false)
public void executeTask() {
System.out.println("Executing task...");
}
}
3. Access the Annotation via Reflection
To retrieve and use the annotation's information at runtime, we'll use Java Reflection.
java
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class AnnotationExample {
public static void main(String[] args) {
try {
// Get the Task class object
Class<Task> obj = Task.class;
// Accessing the annotation on fields
for (Field field : obj.getDeclaredFields()) {
if (field.isAnnotationPresent(TaskInfo.class)) {
TaskInfo annotation = field.getAnnotation(TaskInfo.class);
System.out.println("Field Name: " + field.getName());
System.out.println("Author: " + annotation.author());
System.out.println("Priority: " + annotation.priority());
System.out.println("Completed: " + annotation.completed());
}
}
// Accessing the annotation on methods
for (Method method : obj.getDeclaredMethods()) {
if (method.isAnnotationPresent(TaskInfo.class)) {
TaskInfo annotation = method.getAnnotation(TaskInfo.class);
System.out.println("\nMethod Name: " + method.getName());
System.out.println("Author: " + annotation.author());
System.out.println("Priority: " + annotation.priority());
System.out.println("Completed: " + annotation.completed());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. Run the Example
When you run the AnnotationExample class, it will access and display the annotation values for the fields and methods in the Task class.
Output:
text
Field Name: taskName
Author: John Doe
Priority: HIGH
Completed: true
Method Name: executeTask
Author: Jane Doe
Priority: LOW
Completed: false
Explanation
- Enum
Element: The Priority enum is used to define different levels of
priority, demonstrating how to use enums in annotations.
- Multiple
Target Types: The @Target annotation allows @TaskInfo to be applied to
both fields and methods (ElementType.FIELD, ElementType.METHOD).
- Accessing
Multiple Annotations: The example demonstrates how to access
annotation data from both fields and methods using reflection.
- @Retention:
Specifies how long annotations with the annotated type are to be retained.
RetentionPolicy.RUNTIME means the annotation is available at runtime.
- Home-icon
- DSA
- _Sorting
- __Bubble Sort
- __Selection Sort
- __Insertion Sort
- __Merge Sort
- __Quick Sort
- __Simple Merge Sort
- _Algorithm
- __Multiple Attribute Sort
- __Sort 10 billion numbers
- __Case sensitive sort
- __Different Way Multiplication
- __Different Way Division
- __Karatsubas Algo
- __Date palindrome
- __Binary Tree
- __Two Jar difference
- __100 doors
- __Tiger Goat
- __Find Itinerary
- _Java
- __jdk 1.8 lambdas
- __jdk 1.8 static
- __Serilization
- __Threadpool Execcutor
- __Jvm compiler
- __Print number
- __Multitasking
- __Garbage collection
- __Exception
- __Mutable
- __Break and Continue
- __Clone
- __Enum
- __Inheritance
- _Custom/Generic DS
- __Custom HashMap
- __Custom Stack
- __Custom Doubly Linklist
- __Custom Singlly Linklist
- __Custom Array List
- __Stack Reverse Order
- __Custom Collection Reverse Stack
- _Custom Masking
- __Masking String
- _Miscellaneous
- __Copy Properties
- __Seat Arrangement Sort
- __Number to Word
- __Pascal Triangle
- __Permutaion and Combination
- __Custom Permutaion and Combination
- __Excel file column number
- __Convert Degree to radian
- __Random number Generate
- __Alphanumeric random number
- __File monitoring
- __Jasper report
- __Multiple file read
- Chemical
- _Chemical look
- _Molecular weight
- _Orbitals to electron images using Hund's rule
- Tools
- _Sql
- __Sql query
- __DB lock
- __floating-double
- _NoSql
- __Mongodb install
- __Mongodb load balancer or replica
- __Mongodb shard setup
- __Mongodb connection
- _Stylus Studio
- __Stylus Studio EDI MSG
- __Edifact Message Conveter
- _Miscellaneous Tools
- __Database Rever Engine
- __Hot Swap Tool
- __Hot Deployment Tool
- __Visualvm Monitoring Setup
- __Jconsole Monitoring Setup
- __Postman Setup
- __Remote debug
- __Git Command
- __Apache loadblancer
- Security
- _Encryption
- __Hashmac Algo
- __generating-keystore-files
- __Symetric
- __Asymmetric
- __Asymmetric using 3ds
- __OWASP Top 10
- __HTTP and HTTPS
- _TLS
- __TLS 1.2
- __TLS 1.3 Configuration
- __TLS 1.3 browsers
- _Oauth
- __Oauth 2.0
- __Oauth 2.0 program
- Spring
- _Spring Info
- __Filter
- __Debounce,Throttling, RateLimit and BackOff
- _Microservice
- __Filter
- __Custom Filter
- _SCG
- __rewritepath
- Linux
- _Command
- _Jenkins Pipeline
- _Deployment process
- Design
- _Generic
- __Time Complexity
- __Java Design
- __Master Design Pattern
- __Leaky Bucket Algorithm
- _Cloud
- __Google Cloud Services
- __Cloud Application Tier
- __Cloud Hierarchical
- __Orika mapper
- __Sequence Diagram
0 Comments