KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > etc > injection > TypeCaseInjection


1 package jfun.yan.etc.injection;
2
3
4 import java.util.Hashtable JavaDoc;
5 import java.util.Map JavaDoc;
6
7 import jfun.yan.util.ReflectionUtil;
8
9 /**
10  * The Nut class for type casing Injection objects for different target types.
11  * <p>
12  * @author Ben Yu
13  * Dec 17, 2005 12:21:58 PM
14  */

15 public class TypeCaseInjection implements Injection {
16   private final Class JavaDoc[] types;
17   private final Injection[] cases;
18   
19   private final Map JavaDoc cache = new Hashtable JavaDoc();
20   public boolean inject(Object JavaDoc obj) {
21     if(obj == null) return true;
22     final Class JavaDoc type = obj.getClass();
23     final Object JavaDoc cached = cache.get(type);
24     if(cached!=null){
25       if(cached instanceof Injection){
26         return ((Injection)cached).inject(obj);
27       }
28       else{
29         return false;
30       }
31     }
32     else{
33       for(int i=0; i<types.length; i++){
34         final Class JavaDoc typecase = types[i];
35         final Injection injection = cases[i];
36         if(ReflectionUtil.isAssignableFrom(typecase, type)){
37           final boolean result = injection.inject(obj);
38           if(result){
39             cache.put(type, injection);
40             return true;
41           }
42         }
43       }
44       cache.put(type, Boolean.valueOf(false));
45       return false;
46     }
47   }
48   public TypeCaseInjection(Class JavaDoc[] types, Injection[] cases) {
49     this.cases = cases;
50     this.types = types;
51   }
52 }
53
Popular Tags