基于具体对象类型的Java动态调度方法

时间:2017-07-04 11:55:03

标签: java dispatch

在Java中是否可以根据对象的运行时类型动态调度方法?

定义以下层次结构:

public abstract class AbstractError {...}

public class GenericError extends AbstractError {...}

public class ValidationError extends AbstractError {...}

是否可以进行依赖于AbstractError对象的实际运行时类型的方法调用,例如以下(似乎不起作用)?

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());
}

在Java中可以实现这个或类似的东西吗?

0 个答案:

没有答案