How to find type without using instanceof?

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

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

List criteria = new ArrayList

        
7条回答
  •  旧时难觅i
    2020-12-19 20:36

    Well, you can...

    if (ContextualCriteria.class.equals(c.getClass()) {
    

    ... though it's just a fancier-looking way of writing instanceof. (Well, almost: this tests whether it is exactly the class, rather than the class of a subclass -- for that you want isAssignableFrom()).

    The right way to get rid of the smell is to implement a polymorphic method in Criteria which is overridden in subclasses, for example.

提交回复
热议问题