检查是否注解是一个特定类型的 [英] Checking if an annotation is of a specific type
问题描述
我使用反射,看看是否能连接到一个类的属性的注释,是一种特定类型的。目前我做的:
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())) {
...
}
这令我有点kludgey因为它依赖于一个字符串,它是一个完全合格的类名。如果命名空间在未来发生变化,这可能会导致细微的错误。
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.
我想这样做:
if(Class.forName(annotation.annotationType().getName()).isInstance(
new javax.validation.Valid()
)) {
...
}
但 javax.validation.Valid
是一个抽象类,不能被实例化。有没有一种方法来模拟的instanceof
(或基本使用 isInstance
)对一个接口或抽象类?
But javax.validation.Valid
is 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?
推荐答案
您只是在寻找
if (annotation.annotationType().equals(javax.validation.Valid.class)){}
这篇关于检查是否注解是一个特定类型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!