检查注释是否属于特定类型
我正在使用反射来查看附加到类属性的注释是否属于特定类型。目前我正在做的事情:
if("javax.validation.Valid".equals(annotation.annotationType().getName())) {
...
}
这让我觉得有点麻烦,因为它依赖于一个完全限定的类名字符串。如果命名空间将来发生变化,这可能会导致细微的错误。
我想做:
if(Class.forName(annotation.annotationType().getName()).isInstance(
new javax.validation.Valid()
)) {
...
}
但是 javax.validation.Valid 是一个抽象类,无法实例化。有没有办法针对接口或抽象类模拟 instanceof
(或基本上使用 isInstance
)?
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.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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你只是在寻找吗
?
Are you just looking for
?
或者更简单:
Or even simpler:
只是为了完整起见,另一种可能性是
Just for completeness' sake, another possibility is
好吧,我想我应该在发布问题之前多做一些研究。我发现我可以使用
Class.isAssignableFrom(Class cls)
:这似乎可以完成工作。不过,我不确定使用这种方法是否有任何警告。
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)
:This seems to do the job. I'm not sure if there are any caveats to using this approach, though.
由于注释只是一个类,因此您可以简单地使用 == 比较:
Since an annotation is just a class, you can simply use an == compare: