KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > util > deserializer > DefaultConstructedThreadLocalSerializable


1 package jfun.yan.util.deserializer;
2
3
4 import java.lang.reflect.Constructor JavaDoc;
5 import java.lang.reflect.InvocationTargetException JavaDoc;
6
7 import jfun.yan.ComponentInstantiationException;
8
9 /**
10  * A thread local store that is made serializable
11  * and uses the default constructor of a class to
12  * create the initial value.
13  * <p>
14  * @author Ben Yu
15  * Feb 3, 2006 11:56:51 AM
16  */

17 final class DefaultConstructedThreadLocalSerializable
18   implements java.io.Serializable JavaDoc{
19   public Object JavaDoc get(){
20     return store.get();
21   }
22   private static Constructor JavaDoc getDefaultConstructor(final Class JavaDoc type){
23     try{
24       return type.getConstructor(null);
25     }
26     catch(NoSuchMethodException JavaDoc e){
27       throw new IllegalArgumentException JavaDoc("default constructor of "+type
28           + " not found.");
29     }
30   }
31   private static final class ThreadLocalStore extends ThreadLocal JavaDoc{
32     private final Constructor JavaDoc ctor;
33     ThreadLocalStore(Class JavaDoc type) {
34       this.ctor = getDefaultConstructor(type);
35     }
36     public String JavaDoc toString(){
37       return ctor.getDeclaringClass().getName();
38     }
39     protected Object JavaDoc initialValue() {
40       try{
41         return ctor.newInstance(null);
42       }
43       catch(InstantiationException JavaDoc e){
44         throw new IllegalArgumentException JavaDoc("failed to invoke default constructor of "
45             + ctor.getDeclaringClass());
46       }
47       catch(IllegalAccessException JavaDoc e){
48         throw new IllegalArgumentException JavaDoc("cannot access default constructor of "
49             + ctor.getDeclaringClass());
50       }
51       catch(InvocationTargetException JavaDoc e){
52         throw new ComponentInstantiationException("default constructor failed.",
53             e.getTargetException());
54       }
55     }
56   }
57   public String JavaDoc toString(){
58     return type.getName();
59   }
60   private final Class JavaDoc type;
61   private transient ThreadLocalStore store;
62   private void readObject(java.io.ObjectInputStream JavaDoc in)
63   throws ClassNotFoundException JavaDoc, java.io.IOException JavaDoc{
64     in.defaultReadObject();
65     store = new ThreadLocalStore(type);
66   }
67   public DefaultConstructedThreadLocalSerializable(Class JavaDoc type){
68     this.type = type;
69     this.store = new ThreadLocalStore(type);
70   }
71 }
72
Popular Tags