我有这个注释类型类:

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类对象,并尝试获取有关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

有什么办法可以通过反射获得那些信息吗?

谢谢

最佳答案

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

10-07 17:10