如何从finally块访问方法的结果值
盡管JVM是基于堆棧的計算機 ,但Java語言實際上并沒有為您提供任何訪問該堆棧的方法。 即使有時,在極少數情況下,它也會非常有用。
一個例子
方法結果值放在堆棧中。 如果查看以下示例:
public int method() {if (something)return 1;...if (somethingElse)return 2;...return 0; }如果我們忽略了停機問題 ,錯誤處理,以及其他學術討論,我們可以說,上述方法將“肯定”返回的任何值1 , 2或0 。 并且該值在退出該方法之前被放入堆棧中。
現在,有時,僅當返回給定結果值時才采取一些措施可能是一個用例。 然后,可能會誘使人們開始關于是否有多個return語句為EVIL?的古老爭論 ,而整個方法應該這樣寫:
public int method() {int result = 0;if (something)result = 1;...if (somethingElse)result = 2;...// Important action here prior to returnif (result == 1337)log.info("hehehe ;-)");return result; }當然,上面的示例是錯誤的,因為以前, if (something) return 1而if (something) return 2語句則立即中止方法執行。 為了使用“單返回語句”技術實現相同的目的,我們必須像這樣重寫代碼:
public int method() {int result = 0;if (something)result = 1;else {...if (somethingElse)result = 2;else {...}}// Important action here prior to returnif (result == 1337)log.info("hehehe ;-)");return result; }…并且,當然,我們可以繼續使用花括號和/或壓痕水平線進行騎車脫下和發火警告 ,這表明我們沒有獲得任何好處。
從堆棧訪問返回值
我們在原始實現中真正想做的是在返回之前檢查一下堆棧上的值,即將返回什么值。 這是一些偽Java:
public int method() {try {if (something)return 1;...if (somethingElse)return 2;...return 0;}// Important action here prior to returnfinally {if (reflectionMagic.methodResult == 1337)log.info("hehehe ;-)");} }好消息是:是的,我們可以! 這是實現上述目標的簡單技巧:
public int method() {int result = 0;try {if (something)return result = 1;...if (somethingElse)return result = 2;...return result = 0;}// Important action here prior to returnfinally {if (result == 1337)log.info("hehehe ;-)");} }不太好的消息是:您一定不要忘記顯式分配結果。 但是每隔一段時間,當Java語言實際上不允許您訪問時,此技術對于“訪問方法堆棧”非常有用。
當然…
當然,您也可以在這里訴諸無聊的解決方案:
public int method() {int result = actualMethod();if (result == 1337)log.info("hehehe ;-)");return result; }public int actualMethod() {if (something)return result = 1;...if (somethingElse)return result = 2;...return result = 0; }…而且,也許在大多數情況下,這種技術確實更好(因為更具可讀性)。 但是有時候,您想要做的事情不僅限于登錄該finally塊,或者您想要訪問的不僅僅是結果值,而且您不想重構該方法。
其他方法?
現在輪到你了。 您首選的替代方法是什么(帶有代碼示例?),例如,使用Try monad? 還是方面?
翻譯自: https://www.javacodegeeks.com/2015/05/how-to-access-a-methods-result-value-from-the-finally-block.html
總結
以上是生活随笔為你收集整理的如何从finally块访问方法的结果值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: InterServer vs Blueh
- 下一篇: 9个最佳全球标识以及如何免费制作自己的标