Is it possible in Java to do a kind of dynamically dispatch a method based on the runtime type of an object?
Defining the following hierarchy:
public abstract class AbstractError {...}
public class GenericError extends AbstractError {...}
public class ValidationError extends AbstractError {...}
Would it be possible to have a method invocation that relies on actual runtime type of AbstractError
object such as the following (which seems not work)?
public foo() {
AbstractError error = ....
// Here I want to decide which method to invoke on runtime (based on error concrete type)
MessageItemDTO = buildMessageItem(error);
}
private MessageItemDTO buildMessageItem(GeneralError error) {
// ... call here when error (declared AbstractError) is actually a GeneralError
}
private MessageItemDTO buildMessageItem(ValidationError) {
// ... call here when error (declared AbstractError) is actually a ValidationError
}
private MessageItemDTO buildMessageItem(AbstractError error) {
throw new UnsupportedOperationException("No dispatcher implemented for type: " + error.getClass().getSimpleName());
}
Is it possible to achieve this or something similar in Java?