Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting information about annotation in java via reflection

I have this annotation type class:

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

@Retention(RetentionPolicy.RUNTIME)
public @interface RemoteTcpAccess {

    public int port();
}

and apply it on another class like this:

@RemoteTcpAccess(port = 444)
public class CalculatorService {

    public int Add(int a, int b) {
        return a + b;
    }

    public void DisplayText(String text) {
        System.out.println(text);
    }
}

Now I get the CalculatorService Class object and try to get the information about RemoteTcpAccess annotation:

private static void CheckRemoteTcpAccess(List<Class> classes) {
        for (Class class1 : classes) {
            for (Annotation annotation : class1.getDeclaredAnnotations()) {
                if (AnnotationEquals(annotation, ComponentsProtocol.REMOTE_TCP_ACCESS)) {
             //GET INFORMATION
                }
            }
        }
    }

    private static boolean AnnotationEquals(Annotation classAnnotation, String protocolAnnotation) {
        return classAnnotation.toString()
                .substring(0, classAnnotation.toString().indexOf("("))
                .equals(protocolAnnotation);
    }

I am able to recognize if the class has applied RemoteTcpAccess annotation on it, but I cant get inforamtion about what fields has the annotation and what values have those fields, like :

Field port - value 444

Is there any way how to get those inforamtion via reflection?

thanks

like image 482
John Smith Avatar asked May 21 '26 06:05

John Smith


1 Answers

You can call:

RemoteTcpAccess rta = clazz.getAnnotation(RemoteTcpAccess.class);
if(rta != null) //annotation present at class level
{
int port = rta.port();
}

In your case you can directly use specific annotation (RemoteTcpAccess) instead of generic way of using Annotation. So this will trim down your loop to:

for (Class class1 : classes) {
    RemoteTcpAccess rta = class1.getAnnotation(RemoteTcpAccess.class);
    if(rta != null)  {
       int port = rta.port(); //GET INFORMATION
       ..
    }
 }
like image 80
harsh Avatar answered May 22 '26 21:05

harsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!