1 package org.kohsuke.stapler; 2 3 import java.lang.reflect.InvocationTargetException ; 4 import java.util.HashMap ; 5 import java.util.Map ; 6 7 16 public abstract class TearOffSupport { 17 private volatile Map <Class ,Object > tearOffs; 18 19 public final <T> T getTearOff(Class <T> t) { 20 Map <Class ,Object > m = tearOffs; 21 if(m==null) return null; 22 return (T)m.get(t); 23 } 24 25 public final <T> T loadTearOff(Class <T> t) { 26 T o = getTearOff(t); 27 if(o==null) { 28 try { 29 o = t.getConstructor(getClass()).newInstance(this); 30 setTearOff(t,o); 31 } catch (InstantiationException e) { 32 throw new InstantiationError (e.getMessage()); 33 } catch (IllegalAccessException e) { 34 throw new IllegalAccessError (e.getMessage()); 35 } catch (InvocationTargetException e) { 36 Throwable ex = e.getTargetException(); 37 if(ex instanceof RuntimeException ) 38 throw (RuntimeException )ex; 39 if(ex instanceof Error ) 40 throw (Error )ex; 41 throw new Error (e); 42 } catch (NoSuchMethodException e) { 43 throw new NoSuchMethodError (e.getMessage()); 44 } 45 } 46 return o; 47 } 48 49 public synchronized <T> void setTearOff(Class <T> type, T instance) { 50 Map <Class ,Object > m = tearOffs; 51 Map <Class ,Object > r = m!=null ? new HashMap <Class , Object >(tearOffs) : new HashMap <Class ,Object >(); 52 r.put(type,instance); 53 tearOffs = r; 54 } 55 } 56 | Popular Tags |