3

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

4

4 回答 4

2

您可以致电:

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

在您的情况下,您可以直接使用特定的注释 ( RemoteTcpAccess) 而不是通用的使用方式Annotation。因此,这会将您的循环缩减为:

for (Class class1 : classes) {
    RemoteTcpAccess rta = class1.getAnnotation(RemoteTcpAccess.class);
    if(rta != null)  {
       int port = rta.port(); //GET INFORMATION
       ..
    }
 }
于 2013-07-30T09:29:52.657 回答
1

尝试这个

 ((RemoteTcpAccess)annotation).port();
于 2013-07-30T09:29:38.133 回答
0

代码应该对注解进行类型检查,看是否属于 type RemoteTcpAccess。如果是这样,请将Annotation转换为RemoteTcpAccess类型。可以从这种类型port中检索。

import java.lang.annotation.Annotation;

@RemoteTcpAccess(port = 322)
public class AnnotationTest {

    /**
     * @param args
     * @throws NoSuchFieldException
     * @throws SecurityException
     */
    public static void main(String[] args) throws SecurityException,
            NoSuchFieldException {
        Annotation anno = AnnotationTest.class
                .getAnnotation(RemoteTcpAccess.class);
        if (anno instanceof RemoteTcpAccess) {
            RemoteTcpAccess rta = (RemoteTcpAccess) anno;
            System.out.println(rta.port());
        }
    }
}
于 2013-07-30T09:42:55.537 回答
0

从了解接口和注释之间的类比,我会说这会起作用:

((RemoteTcpAccess) annotation).getPort()
于 2013-07-30T09:29:53.893 回答