1 16 package net.sf.cglib.proxy; 17 18 import net.sf.cglib.core.ReflectUtils; 19 import java.lang.reflect.Method ; 20 import java.util.*; 21 22 25 abstract public class CallbackHelper 26 implements CallbackFilter 27 { 28 private Map methodMap = new HashMap(); 29 private List callbacks = new ArrayList(); 30 31 public CallbackHelper(Class superclass, Class [] interfaces) 32 { 33 List methods = new ArrayList(); 34 Enhancer.getMethods(superclass, interfaces, methods); 35 Map indexes = new HashMap(); 36 for (int i = 0, size = methods.size(); i < size; i++) { 37 Method method = (Method )methods.get(i); 38 Object callback = getCallback(method); 39 if (callback == null) 40 throw new IllegalStateException ("getCallback cannot return null"); 41 boolean isCallback = callback instanceof Callback; 42 if (!(isCallback || (callback instanceof Class ))) 43 throw new IllegalStateException ("getCallback must return a Callback or a Class"); 44 if (i > 0 && ((callbacks.get(i - 1) instanceof Callback) ^ isCallback)) 45 throw new IllegalStateException ("getCallback must return a Callback or a Class consistently for every Method"); 46 Integer index = (Integer )indexes.get(callback); 47 if (index == null) { 48 index = new Integer (callbacks.size()); 49 indexes.put(callback, index); 50 } 51 methodMap.put(method, index); 52 callbacks.add(callback); 53 } 54 } 55 56 abstract protected Object getCallback(Method method); 57 58 public Callback[] getCallbacks() 59 { 60 if (callbacks.size() == 0) 61 return new Callback[0]; 62 if (callbacks.get(0) instanceof Callback) { 63 return (Callback[])callbacks.toArray(new Callback[callbacks.size()]); 64 } else { 65 throw new IllegalStateException ("getCallback returned classes, not callbacks; call getCallbackTypes instead"); 66 } 67 } 68 69 public Class [] getCallbackTypes() 70 { 71 if (callbacks.size() == 0) 72 return new Class [0]; 73 if (callbacks.get(0) instanceof Callback) { 74 return ReflectUtils.getClasses(getCallbacks()); 75 } else { 76 return (Class [])callbacks.toArray(new Class [callbacks.size()]); 77 } 78 } 79 80 public int accept(Method method) 81 { 82 return ((Integer )methodMap.get(method)).intValue(); 83 } 84 85 public int hashCode() 86 { 87 return methodMap.hashCode(); 88 } 89 90 public boolean equals(Object o) 91 { 92 if (o == null) 93 return false; 94 if (!(o instanceof CallbackHelper)) 95 return false; 96 return methodMap.equals(((CallbackHelper)o).methodMap); 97 } 98 } 99 | Popular Tags |