简体   繁体   中英

Object is instanceof two disjoint classes

I built a Wildfly application using javax validations to validate incoming models. Now I am trying to write an Exception mapper that catches any ValidationException.

@Provider
public class MyValidationMapper implements ExceptionMapper<ValidationException> {

    @Override
    public Response toResponse(ValidationException exception) {

        if (exception instanceof ResteasyViolationException) {
            // do something specific
        }

        if (exception instanceof ConstraintViolationException) {
            // do something specific
        }

        // do something generic
    }
}

As you can see I want special treatment for ResteasyViolationException and ConstraintViolationException , both of which are direct subclasses of ValidationException .

The problem is that exception is an instance of both of these types.

System.out.println(exception instanceof ResteasyViolationException);
System.out.println(exception instanceof ConstraintViolationException);

yields true each time. Hence the behaviour of my mapper depends on the order in which I check the exception's type.

How is that possible? Apparently my understanding of instanceof has some gaps. Or is there anything special about Resteasy?

According to the javadoc , org.jboss.resteasy.api.validation.ResteasyViolationException extends javax.validation.ConstraintViolationException , so when handling the latter you'll always be handling the former as well.

An option is to not use instanceof , but check with getClass() for the actual type. However beware of any classloader related weirdnesses.

The underlying problem is that you are taking the wrong conclusions from your observations.

Your observation told you: those two exceptions can't be "disjoint". So the most meaningful response would be to question your own assumption that those two are disjoint; for example by studying javadocs. Which would have told you what Kayamann told you in his answer: those two classes are in fact related to each other.

Meaning: don't assume that a language that does single-inheritance for 20+ years ... all of a sudden "breaks" with that, just because you run into something that seems to contradict this concept.

In other words: always ask yourself first "why do I assume that this or that must be like that" when reality contradicts your expectations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM