1 19 package org.apache.cayenne.reflect; 20 21 import java.lang.reflect.Method ; 22 import java.lang.reflect.Modifier ; 23 24 import org.apache.cayenne.CayenneRuntimeException; 25 import org.apache.cayenne.util.Util; 26 27 35 class CallbackOnListener extends AbstractCallback { 36 37 private Method callbackMethod; 38 private Object listener; 39 40 CallbackOnListener(Object listener, String methodName) 41 throws IllegalArgumentException { 42 this(listener, methodName, Object .class); 43 } 44 45 CallbackOnListener(Object listener, String methodName, Class entityType) 46 throws IllegalArgumentException { 47 48 if (listener == null) { 49 throw new IllegalArgumentException ("Null listener"); 50 } 51 52 this.callbackMethod = findMethod(listener.getClass(), methodName, entityType); 53 this.listener = listener; 54 } 55 56 public void performCallback(Object entity) { 57 try { 58 callbackMethod.invoke(listener, new Object [] { 59 entity 60 }); 61 } 62 catch (Exception e) { 63 throw new CayenneRuntimeException( 64 "Error invoking entity listener callback method " 65 + callbackMethod.getName(), 66 e); 67 } 68 } 69 70 private Method findMethod(Class objectClass, String methodName, Class entityType) 71 throws IllegalArgumentException { 72 73 Method [] methods = objectClass.getDeclaredMethods(); 74 for (int i = 0; i < methods.length; i++) { 75 if (methodName.equals(methods[i].getName())) { 76 77 int modifiers = methods[i].getModifiers(); 80 Class [] parameters = methods[i].getParameterTypes(); 81 if (!Modifier.isStatic(modifiers) 82 && Void.TYPE.isAssignableFrom(methods[i].getReturnType()) 83 && parameters.length == 1 84 && parameters[0].isAssignableFrom(entityType)) { 85 86 if (!Util.isAccessible(methods[i])) { 87 methods[i].setAccessible(true); 88 } 89 90 return methods[i]; 91 } 92 } 93 } 94 95 throw new IllegalArgumentException ("Class " 96 + objectClass.getName() 97 + " has no valid listener callback method '" 98 + methodName 99 + "'"); 100 } 101 } 102 | Popular Tags |