[英]Overloading the getCause() method in a throwable object
如何在throwable對象中重載getCause()方法? 我有以下但它似乎沒有工作,因為它說它不能重載字符串。
public class MyException extends RuntimeException {
String cause;
MyException(String s) {
cause = s;
}
@Overwrite public String getCause() {
return cause;
}
擁有兩種只返回類型不同的方法是違法的。 假設有人寫道:
Object obj = myException.getCause();
這是完全合法的java,編譯器無法弄清楚它是String
版本還是Throwable
版本。
同樣,您無法替換超類簽名,因為這也是完全合法的:
Throwable t = new MyException();
Throwable t0 = t.getCause();
//Returns String?!?!?!?
接受的答案清除了這一點 :
擁有兩種只返回類型不同的方法是違法的
但是如果你遇到這種情況, getCause()
應該在MyException
返回自定義原因,以防原始原因為null。
在這種情況下,您可以使用initCause()
來設置原因並覆蓋toString()
方法。 因此,當在MyException
對象上調用getCause()
方法時,它將顯示來自customCause而不是null的消息。
有什么用:在遺留系統中,如果你在登錄時在MyException
對象上使用了getCause()
,現在你想在不改變代碼的情況下添加自定義原因,這就是方法。
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/文檔/ API / JAVA / LANG / Throwable.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.