检查注释是否属于特定类型 [英] 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())) {
...
}
这让我觉得有点笨拙,因为它依赖于一个完全限定类名的字符串.如果命名空间在未来发生变化,这可能会导致细微的错误.
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屋!
查看全文