Checking if an annotation is of a specific type

后端 未结 5 1566
生来不讨喜
生来不讨喜 2021-02-01 20:57

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\"         


        
相关标签:
5条回答
  • 2021-02-01 21:29

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

    if (annotation.annotationType() == Valid.class) { /* ... */ }
    
    0 讨论(0)
  • 2021-02-01 21:33

    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.

    0 讨论(0)
  • 2021-02-01 21:49

    Are you just looking for

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

    ?

    0 讨论(0)
  • 2021-02-01 21:55

    Or even simpler:

    if (annotation instanceof Valid) { /* ... */ }
    
    0 讨论(0)
  • 2021-02-01 21:55

    Just for completeness' sake, another possibility is

    if (this.getClass().isAnnotationPresent(MyCustomAnnotation.class)) {
    
    0 讨论(0)
提交回复
热议问题