1 package uk.co.jezuk.mango; 2 3 import java.lang.reflect.Method ; 4 5 11 public class Adapt 12 { 13 18 static public UnaryFunction Compose(UnaryFunction f, UnaryFunction g) 19 { 20 final UnaryFunction ff = f; 21 final UnaryFunction gg = g; 22 return new UnaryFunction() { 23 public Object fn(Object x) 24 { 25 return ff.fn(gg.fn(x)); 26 } }; 28 } 30 36 static public BinaryFunction Compose(BinaryFunction f, UnaryFunction g1, UnaryFunction g2) 37 { 38 final BinaryFunction ff = f; 39 final UnaryFunction gg1 = g1; 40 final UnaryFunction gg2 = g2; 41 return new BinaryFunction() { 42 public Object fn(Object x, Object y) 43 { 44 return ff.fn(gg1.fn(x), gg2.fn(y)); 45 } }; 47 } 49 63 static public UnaryFunction Method(final Object obj, String methodName) 64 { 65 return wrapMethod(obj.getClass(), obj, methodName); 66 } 68 76 static public UnaryFunction Method(final Class klass, String methodName) 77 { 78 return wrapMethod(klass, null, methodName); 79 } 81 static private class UnaryMethodNamed implements Predicate 82 { 83 UnaryMethodNamed(String name, int argCount) 84 { 85 name_ = name; 86 argCount_ = argCount; 87 } public boolean test(Object obj) 89 { 90 java.lang.reflect.Method m = (java.lang.reflect.Method )obj; 91 return (m.getName().equals(name_) && (m.getParameterTypes().length == argCount_)); 92 } private String name_; 94 private int argCount_; 95 } 97 static private UnaryFunction wrapMethod(final Class klass, final Object obj, String methodName) 98 { 99 Method [] methods = klass.getMethods(); 100 final Method m = (Method )Algorithms.findIf(java.util.Arrays.asList(methods).iterator(), new UnaryMethodNamed(methodName, 1)); 101 if(m == null) 102 throw new RuntimeException (new NoSuchMethodException ()); 103 104 return new UnaryFunction() { 105 private Object obj_; 106 private Method method_; 107 { obj_ = obj; method_ = m; } 108 public Object fn(Object arg) 109 { 110 Object [] args = new Object []{ arg }; 111 try { 112 return method_.invoke(obj_, args); 113 } catch(Exception e) { 115 throw new RuntimeException (e); 116 } } }; } 121 140 static public UnaryFunction ArgumentMethod(final String methodName) 141 { 142 return new UnaryFunction() { 143 private String methodName_; 144 private Class lastClass_; 145 private Method method_; 146 { methodName_ = methodName; } 147 public Object fn(Object arg) 148 { 149 if(!arg.getClass().equals(lastClass_)) 150 { 151 lastClass_ = arg.getClass(); 152 Method [] methods = lastClass_.getMethods(); 153 method_ = (Method )Algorithms.findIf(java.util.Arrays.asList(methods).iterator(), new UnaryMethodNamed(methodName, 0)); 154 if(method_ == null) 155 throw new RuntimeException (new NoSuchMethodException ()); 156 } 158 try { 159 return method_.invoke(arg, null); 160 } catch(Exception e) { 162 throw new RuntimeException (e); 163 } } }; } 168 private Adapt() { } 170 } | Popular Tags |