How to find type without using instanceof?

后端 未结 7 1755
予麋鹿
予麋鹿 2020-12-19 19:58

I have a List of interface type Criteria within my class Query.

List criteria = new ArrayList

        
相关标签:
7条回答
  • 2020-12-19 20:42

    You can also use:

    for(Criteria c : criteria) {
       if(c.getClass() == ContextualCriteria.class){
           // logic
       }
       if ...
    }
    

    Note that Object#getClass() returns the runtime type of c, so you can't reliably use this if ContextualCriteria can be subclassed for example. To do this you would need to use Class#isAssignableFrom():

    for(Criteria c : criteria) {
       if(ContextualCriteria.class.isAssignableFrom(c)){
           // logic
       }
       if ...
    }
    
    0 讨论(0)
提交回复
热议问题