KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > xml > nuts > optional > TypeCaseNut


1 package jfun.yan.xml.nuts.optional;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.HashMap JavaDoc;
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 /**
12  * This Nut class creates a typecase tag that evaluates to a
13  * {@link jfun.yan.Binder} object.
14  * <p>
15  * Upon receiving a component instance, it checks the type of
16  * the instance and runs the proper Binder object defined in
17  * the corresponding case that matches the type.
18  * </p>
19  * <p>
20  * @author Ben Yu
21  * Nov 10, 2005 12:14:46 AM
22  */

23 public class TypeCaseNut extends BinderNut {
24   private final ArrayList JavaDoc cases = new ArrayList JavaDoc();
25   private Binder def;
26   private final HashMap JavaDoc casemap = new HashMap JavaDoc();
27   public void addCase(BinderCase cs){
28     final Class JavaDoc 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 JavaDoc v)
45       throws Throwable JavaDoc{
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 JavaDoc toString(){
60         return "typecase";
61       }
62     };
63   }
64   private static final Class JavaDoc getType(Object JavaDoc v){
65     return v==null?null:v.getClass();
66   }
67 }
68
Popular Tags