View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.lang3.event;
19  
20  import java.lang.reflect.InvocationHandler;
21  import java.lang.reflect.InvocationTargetException;
22  import java.lang.reflect.Method;
23  import java.lang.reflect.Proxy;
24  import java.util.Arrays;
25  import java.util.HashSet;
26  import java.util.Set;
27  
28  import org.apache.commons.lang3.reflect.MethodUtils;
29  
30  /**
31   * Provides some useful event-based utility methods.
32   *
33   * @since 3.0
34   */
35  public class EventUtils {
36  
37      private static final class EventBindingInvocationHandler implements InvocationHandler {
38          private final Object target;
39          private final String methodName;
40          private final Set<String> eventTypes;
41  
42          /**
43           * Creates a new instance of {@link EventBindingInvocationHandler}.
44           *
45           * @param target the target object for method invocations
46           * @param methodName the name of the method to be invoked
47           * @param eventTypes the names of the supported event types
48           */
49          EventBindingInvocationHandler(final Object target, final String methodName, final String[] eventTypes) {
50              this.target = target;
51              this.methodName = methodName;
52              this.eventTypes = new HashSet<>(Arrays.asList(eventTypes));
53          }
54  
55          /**
56           * Checks whether a method for the passed in parameters can be found.
57           *
58           * @param method the listener method invoked
59           * @return a flag whether the parameters could be matched
60           */
61          private boolean hasMatchingParametersMethod(final Method method) {
62              return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
63          }
64  
65          /**
66           * Handles a method invocation on the proxy object.
67           *
68           * @param proxy the proxy instance
69           * @param method the method to be invoked
70           * @param parameters the parameters for the method invocation
71           * @return the result of the method call
72           * @throws Throwable if an error occurs
73           */
74          @Override
75          public Object invoke(final Object proxy, final Method method, final Object[] parameters) throws Throwable {
76              if (eventTypes.isEmpty() || eventTypes.contains(method.getName())) {
77                  if (hasMatchingParametersMethod(method)) {
78                      return MethodUtils.invokeMethod(target, methodName, parameters);
79                  }
80                  return MethodUtils.invokeMethod(target, methodName);
81              }
82              return null;
83          }
84      }
85  
86      /**
87       * Adds an event listener to the specified source.  This looks for an "add" method corresponding to the event
88       * type (addActionListener, for example).
89       * @param eventSource   the event source
90       * @param listenerType  the event listener type
91       * @param listener      the listener
92       * @param <L>           the event listener type
93       *
94       * @throws IllegalArgumentException if the object doesn't support the listener type
95       */
96      public static <L> void addEventListener(final Object eventSource, final Class<L> listenerType, final L listener) {
97          try {
98              MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
99          } catch (final NoSuchMethodException e) {
100             throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
101                     + " does not have a public add" + listenerType.getSimpleName()
102                     + " method which takes a parameter of type " + listenerType.getName() + ".");
103         } catch (final IllegalAccessException e) {
104             throw new IllegalArgumentException("Class " + eventSource.getClass().getName()
105                     + " does not have an accessible add" + listenerType.getSimpleName ()
106                     + " method which takes a parameter of type " + listenerType.getName() + ".");
107         } catch (final InvocationTargetException e) {
108             throw new IllegalArgumentException("Unable to add listener.", e.getCause());
109         }
110     }
111 
112     /**
113      * Binds an event listener to a specific method on a specific object.
114      *
115      * @param <L>          the event listener type
116      * @param target       the target object
117      * @param methodName   the name of the method to be called
118      * @param eventSource  the object which is generating events (JButton, JList, etc.)
119      * @param listenerType the listener interface (ActionListener.class, SelectionListener.class, etc.)
120      * @param eventTypes   the event types (method names) from the listener interface (if none specified, all will be
121      *                     supported)
122      */
123     public static <L> void bindEventsToMethod(final Object target, final String methodName, final Object eventSource,
124             final Class<L> listenerType, final String... eventTypes) {
125         final L listener = listenerType.cast(Proxy.newProxyInstance(target.getClass().getClassLoader(),
126                 new Class[] { listenerType }, new EventBindingInvocationHandler(target, methodName, eventTypes)));
127         addEventListener(eventSource, listenerType, listener);
128     }
129 }