java 检查注释是否属于特定类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3348363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:25:18  来源:igfitidea点击:

Checking if an annotation is of a specific type

javareflectionannotationsinstanceofisinstance

提问by Vivin Paliath

I am using reflection to see if an annotation that is attached to a property of a class, is of a specific type. Current I am doing:

我正在使用反射来查看附加到类属性的注释是否属于特定类型。目前我正在做:

if("javax.validation.Valid".equals(annotation.annotationType().getName())) {
   ...
}

Which strikes me as a little kludgey because it relies on a string that is a fully-qualified class-name. If the namespace changes in the future, this could cause subtle errors.

这让我觉得有点笨拙,因为它依赖于一个完全限定类名的字符串。如果命名空间在未来发生变化,这可能会导致细微的错误。

I would like to do:

我想要做:

if(Class.forName(annotation.annotationType().getName()).isInstance(
     new javax.validation.Valid()
)) {
   ...
}

But javax.validation.Validis an abstract class and cannot be instantiated. Is there a way to simulate instanceof(or basically use isInstance) against an interface or an abstract class?

但是javax.validation.Valid是抽象类,不能实例化。有没有办法针对接口或抽象类模拟instanceof(或基本上使用isInstance)?

回答by Affe

Are you just looking for

你只是在寻找

if (annotation.annotationType().equals(javax.validation.Valid.class)){}

?

?

回答by yurez

Or even simpler:

或者更简单:

if (annotation instanceof Valid) { /* ... */ }

回答by sleske

Just for completeness' sake, another possibility is

为了完整起见,另一种可能性是

if (this.getClass().isAnnotationPresent(MyCustomAnnotation.class)) {

回答by Vivin Paliath

Ok, I guess I should have done a little more research before posting the question. I discovered that I could use Class.isAssignableFrom(Class<?> cls):

好的,我想我应该在发布问题之前做更多的研究。我发现我可以使用Class.isAssignableFrom(Class<?> cls)

import javax.validation.Valid;

if(Valid.class.isAssignableFrom(annotation.annotationType())) {
   ...
}

This seems to do the job. I'm not sure if there are any caveats to using this approach, though.

这似乎可以完成工作。不过,我不确定使用这种方法是否有任何注意事项。

回答by Jorn

Since an annotation is just a class, you can simply use an == compare:

由于注释只是一个类,您可以简单地使用 == 比较:

if (annotation.annotationType() == Valid.class) { /* ... */ }