Groovy原生是不支持do while的,參考
- groovy - dev > do while
- Migration From Classic to JSR syntax
- Groovy Documentation > Control Structures > Looping
- Rosetta Code > Loops/Do-while Groovy
曲線救國,可以這么用
class Looper { private Closure code static Looper loop( Closure code ) { new Looper(code:code) } void until( Closure test ) { code() while (!test()) { code() } } }
import static Looper.* int i = 0 loop { println("Looping : " + i) i += 1 } until { i == 5 }
注意 until 這里用的是大括號,才能讓條件變成一個閉包
實際使用場景,我們接口中需要調用外部接口,外部接口不是很穩定,容易出錯,所以加入了出錯重試機制,一共重試三次,三次過后還是不行才放棄。
def responseString = null Exception exception = null //出錯重試 int retry = 0 Looper.loop { try{ responseString = HttpUtil.post(url, JSONObject.toJSONString(post), header, 10000, 10000) }catch (Exception ex){ exception = ex }finally{ retry++ } }until { exception == null || retry == 3 } if(exception != null){ throw exception }
