EventHandler.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. /* java.beans.EventHandler
  2. Copyright (C) 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.beans;
  32. import java.lang.reflect.InvocationHandler;
  33. import java.lang.reflect.InvocationTargetException;
  34. import java.lang.reflect.Method;
  35. import java.lang.reflect.Proxy;
  36. /**
  37. * <p>EventHandler forms a bridge between dynamically created listeners and
  38. * arbitrary properties and methods.</p>
  39. *
  40. * <p>You can use this class to easily create listener implementations for
  41. * some basic interactions between an event source and its target. Using
  42. * the three static methods named <code>create</code> you can create
  43. * these listener implementations.</p>
  44. *
  45. * <p>See the documentation of each method for usage examples.</p>
  46. *
  47. * @author Jerry Quinn (jlquinn@optonline.net)
  48. * @author Robert Schuster (thebohemian@gmx.net)
  49. * @since 1.4
  50. */
  51. public class EventHandler implements InvocationHandler
  52. {
  53. // The name of the method that will be implemented. If null, any method.
  54. private String listenerMethod;
  55. // The object to call action on.
  56. private Object target;
  57. // The name of the method or property setter in target.
  58. private String action;
  59. // The property to extract from an event passed to listenerMethod.
  60. private String property;
  61. // The target objects Class.
  62. private Class targetClass;
  63. // String class doesn't already have a capitalize routine.
  64. private String capitalize(String s)
  65. {
  66. return s.substring(0, 1).toUpperCase() + s.substring(1);
  67. }
  68. /**
  69. * Creates a new <code>EventHandler</code> instance.
  70. *
  71. * <p>Typical creation is done with the create method, not by knewing an
  72. * EventHandler.</p>
  73. *
  74. * <p>This constructs an EventHandler that will connect the method
  75. * listenerMethodName to target.action, extracting eventPropertyName from
  76. * the first argument of listenerMethodName. and sending it to action.</p>
  77. *
  78. * <p>Throws a <code>NullPointerException</code> if the <code>target</code>
  79. * argument is <code>null</code>.
  80. *
  81. * @param target Object that will perform the action.
  82. * @param action A property or method of the target.
  83. * @param eventPropertyName A readable property of the inbound event.
  84. * @param listenerMethodName The listener method name triggering the action.
  85. */
  86. public EventHandler(Object target, String action, String eventPropertyName,
  87. String listenerMethodName)
  88. {
  89. this.target = target;
  90. // Retrieving the class is done for two reasons:
  91. // 1) The class object is needed very frequently in the invoke() method.
  92. // 2) The constructor should throw a NullPointerException if target is null.
  93. targetClass = target.getClass();
  94. this.action = action; // Turn this into a method or do we wait till
  95. // runtime
  96. property = eventPropertyName;
  97. listenerMethod = listenerMethodName;
  98. }
  99. /**
  100. * Returns the event property name.
  101. */
  102. public String getEventPropertyName()
  103. {
  104. return property;
  105. }
  106. /**
  107. * Returns the listener's method name.
  108. */
  109. public String getListenerMethodName()
  110. {
  111. return listenerMethod;
  112. }
  113. /**
  114. * Returns the target object.
  115. */
  116. public Object getTarget()
  117. {
  118. return target;
  119. }
  120. /**
  121. * Returns the action method name.
  122. */
  123. public String getAction()
  124. {
  125. return action;
  126. }
  127. // Fetch a qualified property like a.b.c from object o. The properties can
  128. // be boolean isProp or object getProp properties.
  129. //
  130. // Returns a length 2 array with the first entry containing the value
  131. // extracted from the property, and the second entry contains the class of
  132. // the method return type.
  133. //
  134. // We play this game because if the method returns a native type, the return
  135. // value will be a wrapper. If we then take the type of the wrapper and use
  136. // it to locate the action method that takes the native type, it won't match.
  137. private Object[] getProperty(Object o, String prop)
  138. {
  139. // Isolate the first property name from a.b.c.
  140. int pos;
  141. String rest = null;
  142. if ((pos = prop.indexOf('.')) != -1)
  143. {
  144. rest = prop.substring(pos + 1);
  145. prop = prop.substring(0, pos);
  146. }
  147. // Find a method named getProp. It could be isProp instead.
  148. Method getter;
  149. try
  150. {
  151. // Look for boolean property getter isProperty
  152. getter = o.getClass().getMethod("is" + capitalize(prop));
  153. }
  154. catch (NoSuchMethodException nsme1)
  155. {
  156. try {
  157. // Look for regular property getter getProperty
  158. getter = o.getClass().getMethod("get" + capitalize(prop));
  159. } catch(NoSuchMethodException nsme2) {
  160. try {
  161. // Finally look for a method of the name prop
  162. getter = o.getClass().getMethod(prop);
  163. } catch(NoSuchMethodException nsme3) {
  164. // Ok, give up with an intelligent hint for the user.
  165. throw new RuntimeException("Method not called: Could not find a property or method '" + prop
  166. + "' in " + o.getClass() + " while following the property argument '" + property + "'.");
  167. }
  168. }
  169. }
  170. try {
  171. Object val = getter.invoke(o);
  172. if (rest != null)
  173. return getProperty(val, rest);
  174. return new Object[] {val, getter.getReturnType()};
  175. } catch(InvocationTargetException ite) {
  176. throw new RuntimeException("Method not called: Property or method '" + prop + "' has thrown an exception.", ite);
  177. } catch(IllegalAccessException iae) {
  178. // This cannot happen because we looked up method with Class.getMethod()
  179. // which returns public methods only.
  180. throw (InternalError) new InternalError("Non-public method was invoked.").initCause(iae);
  181. }
  182. }
  183. /**
  184. * Invokes the <code>EventHandler</code>.
  185. *
  186. * <p>This method is normally called by the listener's proxy implementation.</p>
  187. *
  188. * @param proxy The listener interface that is implemented using
  189. * the proxy mechanism.
  190. * @param method The method that was called on the proxy instance.
  191. * @param arguments The arguments which where given to the method.
  192. * @throws Throwable <code>NoSuchMethodException</code> is thrown when the EventHandler's
  193. * action method or property cannot be found.
  194. */
  195. public Object invoke(Object proxy, Method method, Object[] arguments)
  196. {
  197. try {
  198. // The method instance of the target object. We have to find out which
  199. // one we have to invoke.
  200. Method actionMethod = null;
  201. // Listener methods that weren't specified are ignored. If listenerMethod
  202. // is null, then all listener methods are processed.
  203. if (listenerMethod != null && !method.getName().equals(listenerMethod))
  204. return null;
  205. // If a property is defined we definitely need a valid object at
  206. // arguments[0] that can be used to retrieve a value to which the
  207. // property of the target gets set.
  208. if(property != null) {
  209. // Extracts the argument. We will let it fail with a NullPointerException
  210. // the caller used a listener method that has no arguments.
  211. Object event = arguments[0];
  212. // Obtains the property XXX propertyType keeps showing up null - why?
  213. // because the object inside getProperty changes, but the ref variable
  214. // can't change this way, dolt! need a better way to get both values out
  215. // - need method and object to do the invoke and get return type
  216. Object v[] = getProperty(event, property);
  217. Object[] args = new Object[] { v[0] };
  218. // Changes the class array that controls which method signature we are going
  219. // to look up in the target object.
  220. Class[] argTypes = new Class[] { initClass((Class) v[1]) };
  221. // Tries to find a setter method to which we can apply the
  222. while(argTypes[0] != null) {
  223. try
  224. {
  225. // Look for a property setter for action.
  226. actionMethod = targetClass.getMethod("set" + capitalize(action), argTypes);
  227. return actionMethod.invoke(target, args);
  228. }
  229. catch (NoSuchMethodException e)
  230. {
  231. // If action as property didn't work, try as method later.
  232. }
  233. argTypes[0] = nextClass(argTypes[0]);
  234. }
  235. // We could not find a suitable setter method. Now we try again interpreting
  236. // action as the method name itself.
  237. // Since we probably have changed the block local argTypes array
  238. // we need to rebuild it.
  239. argTypes = new Class[] { initClass((Class) v[1]) };
  240. // Tries to find a setter method to which we can apply the
  241. while(argTypes[0] != null) {
  242. try
  243. {
  244. actionMethod = targetClass.getMethod(action, argTypes);
  245. return actionMethod.invoke(target, args);
  246. }
  247. catch (NoSuchMethodException e)
  248. {
  249. }
  250. argTypes[0] = nextClass(argTypes[0]);
  251. }
  252. throw new RuntimeException("Method not called: Could not find a public method named '"
  253. + action + "' in target " + targetClass + " which takes a '"
  254. + v[1] + "' argument or a property of this type.");
  255. }
  256. // If property was null we will search for a no-argument method here.
  257. // Note: The ordering of method lookups is important because we want to prefer no-argument
  258. // calls like the JDK does. This means if we have actionMethod() and actionMethod(Event) we will
  259. // call the first *EVEN* if we have a valid argument for the second method. This is behavior compliant
  260. // to the JDK.
  261. // If actionMethod() is not available but there is a actionMethod(Event) we take this. That makes us
  262. // more specification compliant than the JDK itself because this one will fail in such a case.
  263. try
  264. {
  265. actionMethod = targetClass.getMethod(action);
  266. }
  267. catch(NoSuchMethodException nsme)
  268. {
  269. // Note: If we want to be really strict the specification says that a no-argument method should
  270. // accept an EventObject (or subclass I guess). However since the official implementation is broken
  271. // anyways, it's more flexible without the EventObject restriction and we are compatible on everything
  272. // else this can stay this way.
  273. if(arguments != null && arguments.length >= 1/* && arguments[0] instanceof EventObject*/) {
  274. Class[] targetArgTypes = new Class[] { initClass(arguments[0].getClass()) };
  275. while(targetArgTypes[0] != null) {
  276. try
  277. {
  278. // If no property exists we expect the first element of the arguments to be
  279. // an EventObject which is then applied to the target method.
  280. actionMethod = targetClass.getMethod(action, targetArgTypes);
  281. return actionMethod.invoke(target, new Object[] { arguments[0] });
  282. }
  283. catch(NoSuchMethodException nsme2)
  284. {
  285. }
  286. targetArgTypes[0] = nextClass(targetArgTypes[0]);
  287. }
  288. }
  289. }
  290. // If we do not have a Method instance at this point this means that all our tries
  291. // failed. The JDK throws an ArrayIndexOutOfBoundsException in this case.
  292. if(actionMethod == null)
  293. throw new ArrayIndexOutOfBoundsException(0);
  294. // Invoke target.action(property)
  295. return actionMethod.invoke(target);
  296. } catch(InvocationTargetException ite) {
  297. throw new RuntimeException(ite.getCause());
  298. } catch(IllegalAccessException iae) {
  299. // Cannot happen because we always use getMethod() which returns public
  300. // methods only. Otherwise there is something seriously broken in
  301. // GNU Classpath.
  302. throw (InternalError) new InternalError("Non-public method was invoked.").initCause(iae);
  303. }
  304. }
  305. /**
  306. * <p>Returns the primitive type for every wrapper class or the
  307. * class itself if it is no wrapper class.</p>
  308. *
  309. * <p>This is needed because to be able to find both kinds of methods:
  310. * One that takes a wrapper class as the first argument and one that
  311. * accepts a primitive instead.</p>
  312. */
  313. private Class initClass(Class klass) {
  314. if(klass == Boolean.class) {
  315. return Boolean.TYPE;
  316. } else if(klass == Byte.class) {
  317. return Byte.TYPE;
  318. } else if(klass == Short.class) {
  319. return Short.TYPE;
  320. } else if(klass == Integer.class) {
  321. return Integer.TYPE;
  322. } else if(klass == Long.class) {
  323. return Long.TYPE;
  324. } else if(klass == Float.class) {
  325. return Float.TYPE;
  326. } else if(klass == Double.class) {
  327. return Double.TYPE;
  328. } else {
  329. return klass;
  330. }
  331. }
  332. /**
  333. *
  334. *
  335. * @param klass
  336. * @return
  337. */
  338. private Class nextClass(Class klass) {
  339. if(klass == Boolean.TYPE) {
  340. return Boolean.class;
  341. } else if(klass == Byte.TYPE) {
  342. return Byte.class;
  343. } else if(klass == Short.TYPE) {
  344. return Short.class;
  345. } else if(klass == Integer.TYPE) {
  346. return Integer.class;
  347. } else if(klass == Long.TYPE) {
  348. return Long.class;
  349. } else if(klass == Float.TYPE) {
  350. return Float.class;
  351. } else if(klass == Double.TYPE) {
  352. return Double.class;
  353. } else {
  354. return klass.getSuperclass();
  355. }
  356. }
  357. /**
  358. * <p>Constructs an implementation of <code>listenerInterface</code>
  359. * to dispatch events.</p>
  360. *
  361. * <p>You can use such an implementation to simply call a public
  362. * no-argument method of an arbitrary target object or to forward
  363. * the first argument of the listener method to the target method.</p>
  364. *
  365. * <p>Call this method like:</p>
  366. * <code>
  367. * button.addActionListener((ActionListener)
  368. * EventHandler.create(ActionListener.class, target, "dispose"));
  369. * </code>
  370. *
  371. * <p>to achieve the following behavior:</p>
  372. * <code>
  373. * button.addActionListener(new ActionListener() {
  374. * public void actionPerformed(ActionEvent ae) {
  375. * target.dispose();
  376. * }
  377. * });
  378. * </code>
  379. *
  380. * <p>That means if you need a listener implementation that simply calls a
  381. * a no-argument method on a given instance for <strong>each</strong>
  382. * method of the listener interface.</p>
  383. *
  384. * <p>Note: The <code>action</code> is interpreted as a method name. If your target object
  385. * has no no-argument method of the given name the EventHandler tries to find
  386. * a method with the same name but which can accept the first argument of the
  387. * listener method. Usually this will be an event object but any other object
  388. * will be forwarded, too. Keep in mind that using a property name instead of a
  389. * real method here is wrong and will throw an <code>ArrayIndexOutOfBoundsException</code>
  390. * whenever one of the listener methods is called.<p/>
  391. *
  392. * <p>The <code>EventHandler</code> will automatically convert primitives
  393. * to their wrapper class and vice versa. Furthermore it will call
  394. * a target method if it accepts a superclass of the type of the
  395. * first argument of the listener method.</p>
  396. *
  397. * <p>In case that the method of the target object throws an exception
  398. * it will be wrapped in a <code>RuntimeException</code> and thrown out
  399. * of the listener method.</p>
  400. *
  401. * <p>In case that the method of the target object cannot be found an
  402. * <code>ArrayIndexOutOfBoundsException</code> will be thrown when the
  403. * listener method is invoked.</p>
  404. *
  405. * <p>A call to this method is equivalent to:
  406. * <code>create(listenerInterface, target, action, null, null)</code></p>
  407. *
  408. * @param listenerInterface Listener interface to implement.
  409. * @param target Object to invoke action on.
  410. * @param action Target property or method to invoke.
  411. * @return A constructed proxy object.
  412. */
  413. public static <T> T create(Class<T> listenerInterface, Object target,
  414. String action)
  415. {
  416. return create(listenerInterface, target, action, null, null);
  417. }
  418. /**
  419. * <p>Constructs an implementation of <code>listenerInterface</code>
  420. * to dispatch events.</p>
  421. *
  422. * <p>Use this method if you want to create an implementation that retrieves
  423. * a property value from the <b>first</b> argument of the listener method
  424. * and applies it to the target's property or method. This first argument
  425. * of the listener is usually an event object but any other object is
  426. * valid, too.</p>
  427. *
  428. * <p>You can set the value of <code>eventPropertyName</code> to "prop"
  429. * to denote the retrieval of a property named "prop" from the event
  430. * object. In case that no such property exists the <code>EventHandler</code>
  431. * will try to find a method with that name.</p>
  432. *
  433. * <p>If you set <code>eventPropertyName</code> to a value like this "a.b.c"
  434. * <code>EventHandler</code> will recursively evaluate the properties "a", "b"
  435. * and "c". Again if no property can be found the <code>EventHandler</code>
  436. * tries a method name instead. This allows mixing the names, too: "a.toString"
  437. * will retrieve the property "a" from the event object and will then call
  438. * the method "toString" on it.</p>
  439. *
  440. * <p>An exception thrown in any of these methods will provoke a
  441. * <code>RuntimeException</code> to be thrown which contains an
  442. * <code>InvocationTargetException</code> containing the triggering exception.</p>
  443. *
  444. * <p>If you set <code>eventPropertyName</code> to a non-null value the
  445. * <code>action</code> parameter will be interpreted as a property name
  446. * or a method name of the target object.</p>
  447. *
  448. * <p>Any object retrieved from the event object and applied to the
  449. * target will converted from primitives to their wrapper class or
  450. * vice versa or applied to a method that accepts a superclass
  451. * of the object.</p>
  452. *
  453. * <p>Examples:</p>
  454. * <p>The following code:</p><code>
  455. * button.addActionListener(
  456. * new ActionListener() {
  457. * public void actionPerformed(ActionEvent ae) {
  458. * Object o = ae.getSource().getClass().getName();
  459. * textField.setText((String) o);
  460. * }
  461. * });
  462. * </code>
  463. *
  464. * <p>Can be expressed using the <code>EventHandler</code> like this:</p>
  465. * <p>
  466. * <code>button.addActionListener((ActionListener)
  467. * EventHandler.create(ActionListener.class, textField, "text", "source.class.name");
  468. * <code>
  469. * </p>
  470. *
  471. * <p>As said above you can specify the target as a method, too:</p>
  472. * <p>
  473. * <code>button.addActionListener((ActionListener)
  474. * EventHandler.create(ActionListener.class, textField, "setText", "source.class.name");
  475. * <code>
  476. * </p>
  477. *
  478. * <p>Furthermore you can use method names in the property:</p>
  479. * <p>
  480. * <code>button.addActionListener((ActionListener)
  481. * EventHandler.create(ActionListener.class, textField, "setText", "getSource.getClass.getName");
  482. * <code>
  483. * </p>
  484. *
  485. * <p>Finally you can mix names:</p>
  486. * <p>
  487. * <code>button.addActionListener((ActionListener)
  488. * EventHandler.create(ActionListener.class, textField, "setText", "source.getClass.name");
  489. * <code>
  490. * </p>
  491. *
  492. * <p>A call to this method is equivalent to:
  493. * <code>create(listenerInterface, target, action, null, null)</code>
  494. * </p>
  495. *
  496. * @param listenerInterface Listener interface to implement.
  497. * @param target Object to invoke action on.
  498. * @param action Target property or method to invoke.
  499. * @param eventPropertyName Name of property to extract from event.
  500. * @return A constructed proxy object.
  501. */
  502. public static <T> T create(Class<T> listenerInterface, Object target,
  503. String action, String eventPropertyName)
  504. {
  505. return create(listenerInterface, target, action, eventPropertyName, null);
  506. }
  507. /**
  508. * <p>Constructs an implementation of <code>listenerInterface</code>
  509. * to dispatch events.</p>
  510. *
  511. * <p>Besides the functionality described for {@link create(Class, Object, String)}
  512. * and {@link create(Class, Object, String, String)} this method allows you
  513. * to filter the listener method that should have an effect. Look at these
  514. * method's documentation for more information about the <code>EventHandler</code>'s
  515. * usage.</p>
  516. *
  517. * <p>If you want to call <code>dispose</code> on a <code>JFrame</code> instance
  518. * when the <code>WindowListener.windowClosing()</code> method was invoked use
  519. * the following code:</p>
  520. * <p>
  521. * <code>
  522. * EventHandler.create(WindowListener.class, jframeInstance, "dispose", null, "windowClosing");
  523. * </code>
  524. * </p>
  525. *
  526. * <p>A <code>NullPointerException</code> is thrown if the <code>listenerInterface</code>
  527. * or <code>target</code> argument are <code>null</code>.
  528. *
  529. * @param listenerInterface Listener interface to implement.
  530. * @param target Object to invoke action on.
  531. * @param action Target method name to invoke.
  532. * @param eventPropertyName Name of property to extract from event.
  533. * @param listenerMethodName Listener method to implement.
  534. * @return A constructed proxy object.
  535. */
  536. public static <T> T create(Class<T> listenerInterface, Object target,
  537. String action, String eventPropertyName,
  538. String listenerMethodName)
  539. {
  540. // Create EventHandler instance
  541. EventHandler eh = new EventHandler(target, action, eventPropertyName,
  542. listenerMethodName);
  543. // Create proxy object passing in the event handler
  544. Object proxy = Proxy.newProxyInstance(listenerInterface.getClassLoader(),
  545. new Class<?>[] {listenerInterface},
  546. eh);
  547. return (T) proxy;
  548. }
  549. }