| 1 package jfun.yan.xml.nuts.optional; 2 3 import java.util.ArrayList ; 4 import java.util.HashMap ; 5 6 import jfun.util.Misc; 7 import jfun.yan.Binder; 8 import jfun.yan.Creator; 9 import jfun.yan.xml.nut.BinderNut; 10 11 23 public class TypeCaseNut extends BinderNut { 24 private final ArrayList cases = new ArrayList (); 25 private Binder def; 26 private final HashMap casemap = new HashMap (); 27 public void addCase(BinderCase cs){ 28 final Class type = cs.getType(); 29 if(casemap.containsKey(type)){ 30 raise("duplicate case: "+Misc.getTypeName(type)); 31 } 32 casemap.put(type, cs); 33 cases.add(cs); 34 } 35 public void addDefault(BinderDefault def){ 36 checkDuplicate("default", this.def); 37 this.def = def.getBinder(); 38 } 39 public Binder eval(){ 40 if(cases.isEmpty() && def==null){ 41 throw raise("empty " + getTagName()); 42 } 43 return new Binder(){ 44 public Creator bind(Object v) 45 throws Throwable { 46 final int sz = cases.size(); 47 for(int i=0; i<sz; i++){ 48 final BinderCase bc = (BinderCase)cases.get(i); 49 if(bc.getType().isInstance(v)){ 50 return bc.getBinder().bind(v); 51 } 52 } 53 if(def!=null) 54 return def.bind(v); 55 else 56 throw raise("unmatched type case for " 57 + Misc.getTypeName(getType(v))); 58 } 59 public String toString(){ 60 return "typecase"; 61 } 62 }; 63 } 64 private static final Class getType(Object v){ 65 return v==null?null:v.getClass(); 66 } 67 } 68 | Popular Tags |