Header Ads Widget

Responsive Advertisement

Custom Annotation of a Service class Example

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

     

    Custom Annotation @TaskInfo
    Custom Annotation @TaskInfo



Post a Comment

0 Comments