gpt4 book ai didi

java - 在界面上查找注释

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:13:33 24 4
gpt4 key购买 nike

我有一个带有实现 Bar 的接口(interface) Foo。接口(interface) Foo 有一个带有方法注释 @Secured 的方法“doMe()”。这是唯一安全的方法。

现在我编写了以下代码来遍历类并查找带有@Secured 的方法。 (此方法尚未完成,我正在尝试通过第一个单元测试。)

  /**
* Determine if a method is secured
* @param method the method being checked
* @return true if the method is secured, false otherwise
*/
protected static boolean isSecured(Method method) {
boolean secured = false;
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation:annotations){
if(Secured.class.equals(annotation.getClass())){
secured = true;
break;
}
}

if(secured){
return true;
}

return secured;
}

除 doMe() 之外的方法在 getAnnotations() 上为 Foo 和 Bar 返回 0 个成员。问题是 doMe() 也为 Foo 和 Bar 返回 0 个成员。

我正在寻找比我更了解反射的人,因为这应该不难找到。 :)

谢谢。

最佳答案

您是否确保注释在运行时可见?您可能需要使用 @Retention(RetentionPolicy.RUNTIME) 来注释您的注释。默认情况下,CLASS 不会在反射方法中返回注释。

另请参阅:RetentionPolicy docs

关于java - 在界面上查找注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13014084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com