Created
March 19, 2011 11:56
-
-
Save guillaumebort/877428 to your computer and use it in GitHub Desktop.
For play.libs.F ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package scrapbook; | |
import java.lang.reflect.InvocationTargetException; | |
public class Test { | |
public static void main(String[] args) { | |
// Standard function | |
Function<String,String> toUpperCase = new Function<String,String>() {{ b = a.toUpperCase(); }}; | |
assertTrue( toUpperCase.invoke("kiki").equals("KIKI") ); | |
// Closure | |
final Integer maxLength = 6; | |
Function<String,Boolean> isLengthOk = new Function<String, Boolean>() {{ b = a.length() <= maxLength; }}; | |
assertTrue( isLengthOk.invoke("coco") == true ); | |
assertTrue( isLengthOk.invoke("guillaume") == false ); | |
} | |
// ----- With: | |
public static void assertTrue(Boolean v) { | |
if(!v) throw new RuntimeException("Assertion failed"); | |
} | |
public static class Val<T> { | |
T t; | |
public Val(T t) { | |
this.t = t; | |
} | |
} | |
public static abstract class Function<A, B> { | |
A a; | |
B b; | |
private Function() { | |
try { | |
if (input.get() != null) { | |
a = ((Val<A>) input.get()).t; | |
} else { | |
_closedValues = new Object[this.getClass().getDeclaredFields().length]; | |
for (int i = 0; i < _closedValues.length; i++) { | |
_closedValues[i] = this.getClass().getDeclaredFields()[i].get(this); | |
} | |
a = (A)""; | |
} | |
} catch (Exception e) { | |
throw new RuntimeException("Function declaration", e); | |
} | |
} | |
private Object[] _closedValues; | |
static final ThreadLocal<Val> input = new ThreadLocal<Val>(); | |
public B invoke(A a) { | |
input.set(new Val<A>(a)); | |
try { | |
Function<A, B> invoked = (Function<A, B>) this.getClass().getDeclaredConstructors()[0].newInstance(_closedValues); | |
return invoked.b; | |
} catch (InvocationTargetException e) { | |
throw new RuntimeException("Function invocation exception", e.getTargetException()); | |
} catch (Exception e) { | |
throw new RuntimeException("Function instantiation exception", e); | |
} finally { | |
input.remove(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment