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