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

发布于 2024-09-11 15:41:49 字数 496 浏览 5 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

去了角落 2024-09-18 15:41:49

你只是在寻找吗

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

Are you just looking for

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

?

转身以后 2024-09-18 15:41:49

或者更简单:

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

Or even simpler:

if (annotation instanceof Valid) { /* ... */ }
只有影子陪我不离不弃 2024-09-18 15:41:49

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

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

Just for completeness' sake, another possibility is

if (this.getClass().isAnnotationPresent(MyCustomAnnotation.class)) {
饭团 2024-09-18 15:41:49

好吧,我想我应该在发布问题之前多做一些研究。我发现我可以使用 Class.isAssignableFrom(Class cls)

import javax.validation.Valid;

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

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

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):

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.

茶色山野 2024-09-18 15:41:49

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

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

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

if (annotation.annotationType() == Valid.class) { /* ... */ }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文