Class for faking Using in Java
Now updated to include significantly less evil. (It no longer needs the _return method...)
1 2 public abstract class Use<T> 3 { 4 private boolean live = false; 5 6 protected final void isLive() 7 { 8 return live; 9 } 10 11 /** 12 * Override this to provide initialisation code for this Use class. This will always be called before 13 * the body is executed. 14 */ 15 protected void start() 16 { 17 } 18 19 /** 20 * Override this to provide finalisation code for this Use class. This will always be called at the end 21 * of use() execution. 22 */ 23 protected void finish() 24 { 25 } 26 27 /** 28 * The body of the code to execute. Returning a value from this should execute _return(T value). 29 */ 30 protected abstract T body(); 31 32 /** 33 * Returns body(), or null if this was never invoked. This will call 34 * all neccessary initialisation and finalisation code. 35 */ 36 public final T use() 37 { 38 try 39 { 40 start(); 41 live = true; 42 43 return body(); 44 } 45 finally 46 { 47 live = false; 48 finish(); 49 } 50 } 51 52 }