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