Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java Runtime annotation work internally? [closed]

I am aware of the compile time annotation functionality, that annotation processor is run and reflection API is used. But I am not sure how a JVM gets notified with respect to a runtime annotation. Does annotation processor come into work here too?

like image 508
javaAndBeyond Avatar asked Feb 07 '23 12:02

javaAndBeyond


1 Answers

Using the meta-annotation @Retention value RetentionPolicy.RUNTIME, the marked annotation is retained by the JVM so it can be used by the runtime environment. This will allow the annotation information (metadata) to be available for examination during runtime.

An example declaration for this is:

package annotations;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
    String value();
}

Runtime The value name itself says that when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime. We can write custom code using reflection package and parse the annotation.

How is it used?

package annotations;
import java.net.Socket;

public class MyClassImpl {

    @Developer("droy")
    public static void connect2Exchange(Socket sock) {
        // do something here
        System.out.println("Demonstration example for Runtime annotations");
    }
}

We can use reflection package to read annotations. It is useful when we develop tools to automate a certain process based on annotation.

package annotations;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class TestRuntimeAnnotation {
    public static void main(String args[]) throws SecurityException,
    ClassNotFoundException {
        for (Method method : Class.forName("annotations.MyClassImpl").getMethods()) {
            if(method.isAnnotationPresent(annotations.Developer.class)){
                try {
                    for (Annotation anno : method.getDeclaredAnnotations())  {
                        System.out.println("Annotation in Method '" + method + "' : " + anno);

                        Developer a = method.getAnnotation(Developer.class);
                        System.out.println("Developer Name:" + a.value());
                    }
                } catch (Throwable ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

Output
Annotation in Method 'public static void annotations.MyClassImpl.connect2Exchange(java.net.Socket)' : @annotations.Developer(value=droy)
Developer Name:droy

like image 85
The Roy Avatar answered Feb 10 '23 03:02

The Roy