0

如何在可抛出对象中重载 getCause() 方法?我有以下内容,但它似乎不起作用,因为它说它不能用字符串重载。

public class MyException extends RuntimeException   {
String cause;
MyException(String s)   {
    cause = s;
}
@Overwrite public String getCause()    {
    return cause;
}
4

2 回答 2

2

拥有两个仅返回类型不同的方法是非法的。假设有人写道:

Object obj = myException.getCause();

那是完全合法的java,编译器无法确定它是String版本还是Throwable版本。

同样,您不能替换超类签名,因为这也是完全合法的:

Throwable t = new MyException();
Throwable t0 = t.getCause();
//Returns String?!?!?!?
于 2013-03-04T19:55:34.293 回答
0

接受的答案清楚了这一点

拥有两个仅返回类型不同的方法是非法的

但是如果你有一种情况,getCause()应该返回自定义原因MyException,以防原始原因为空。

在这种情况下,您可以使用initCause()设置原因和覆盖toString()方法。因此,当getCause()在 的对象上调用方法时MyException,它将显示来自 customCause 的消息,而不是 null。

有什么用:在遗留系统中,如果您在记录时使用getCause()MyException对象,现在您想在不更改大量代码的情况下向其添加自定义原因,这就是方法。

    public class MyException extends RuntimeException {
        String customCause;

        MyException(String s) {
            super(s);
            customCause = s;
        }

        @Override
        public synchronized Throwable getCause() {
            if (super.getCause() != null) {
                return this;
            } else {
                this.initCause(new Throwable(customCause));
                return this;
            }
        }

        @Override
        public String toString() {
            String s = getClass().getName();
            String message = getLocalizedMessage();
            if (message == null) {
                message = customCause;
            }
            return (message != null) ? (s + ": " + message) : s;
        }
    }

参考资料: https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#initCause(java.lang.Throwable) https://docs.oracle.com/javase/7/ docs/api/java/lang/Throwable.html

于 2018-06-20T11:14:30.527 回答