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



我有一个注释类型类:

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 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
       ..
    }
 }

试试这个

 ((RemoteTcpAccess)annotation).port();

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

通过了解接口和注释之间的analogy,我认为这是可行的:

((RemoteTcpAccess) annotation).getPort()

相关内容

  • 没有找到相关文章

最新更新