通过反射获取有关java中注释的信息

时间:2013-07-30 09:25:15

标签: java reflection annotations

我有这个注释类型类:

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

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

    public int port();
}

并将其应用于另一个类:

@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);
    }
}

现在我获取了CalculatorService Class对象并尝试获取有关RemoteTcpAccess注释的信息:

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);
    }

我能够识别该类是否已对其应用RemoteTcpAccess注释,但我无法获得有关注释的哪些字段以及具有这些字段的值的信息,例如:

字段端口 - 值444

有没有办法通过反思获得这些信息?

感谢

4 个答案:

答案 0 :(得分: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
       ..
    }
 }

答案 1 :(得分:1)

试试这个

 ((RemoteTcpAccess)annotation).port();

答案 2 :(得分:0)

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

((RemoteTcpAccess) annotation).getPort()

答案 3 :(得分:0)

代码应该键入检查注释以查看类型是否为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());
        }
    }
}