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.Method;
22  import java.lang.reflect.Proxy;
23  import java.util.Arrays;
24  import java.util.HashSet;
25  import java.util.Set;
26  
27  import org.apache.commons.lang3.reflect.MethodUtils;
28  
29  /**
30   * Provides some useful event-based utility methods.
31   *
32   * @since 3.0
33   */
34  public class EventUtils {
35  
36      private static final class EventBindingInvocationHandler implements InvocationHandler {
37          private final Object target;
38          private final String methodName;
39          private final Set<String> eventTypes;
40  
41          /**
42           * Creates a new instance of {@link EventBindingInvocationHandler}.
43           *
44           * @param target the target object for method invocations
45           * @param methodName the name of the method to be invoked
46           * @param eventTypes the names of the supported event types
47           */
48          EventBindingInvocationHandler(final Object target, final String methodName, final String[] eventTypes) {
49              this.target = target;
50              this.methodName = methodName;
51              this.eventTypes = new HashSet<>(Arrays.asList(eventTypes));
52          }
53  
54          /**
55           * Checks whether a method for the passed in parameters can be found.
56           *
57           * @param method the listener method invoked
58           * @return a flag whether the parameters could be matched
59           */
60          private boolean hasMatchingParametersMethod(final Method method) {
61              return MethodUtils.getAccessibleMethod(target.getClass(), methodName, method.getParameterTypes()) != null;
62          }
63  
64          /**
65           * Handles a method invocation on the proxy object.
66           *
67           * @param proxy the proxy instance
68           * @param method the method to be invoked
69           * @param parameters the parameters for the method invocation
70           * @return the result of the method call
71           * @throws Throwable if an error occurs
72           */
73          @Override
74          public Object invoke(final Object proxy, final Method method, final Object[] parameters) throws Throwable {
75              if (eventTypes.isEmpty() || eventTypes.contains(method.getName())) {
76                  if (hasMatchingParametersMethod(method)) {
77                      return MethodUtils.invokeMethod(target, methodName, parameters);
78                  }
79                  return MethodUtils.invokeMethod(target, methodName);
80              }
81              return null;
82          }
83      }
84  
85      /**
86       * Adds an event listener to the specified source.  This looks for an "add" method corresponding to the event
87       * type (addActionListener, for example).
88       * @param eventSource   the event source
89       * @param listenerType  the event listener type
90       * @param listener      the listener
91       * @param <L>           the event listener type
92       *
93       * @throws IllegalArgumentException if the object doesn't support the listener type
94       */
95      public static <L> void addEventListener(final Object eventSource, final Class<L> listenerType, final L listener) {
96          try {
97              MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
98          } catch (final ReflectiveOperationException e) {
99              throw new IllegalArgumentException("Unable to add listener for class " + eventSource.getClass().getName()
100                     + " and public add" + listenerType.getSimpleName()
101                     + " method which takes a parameter of type " + listenerType.getName() + ".");
102         }
103     }
104 
105     /**
106      * Binds an event listener to a specific method on a specific object.
107      *
108      * @param <L>          the event listener type
109      * @param target       the target object
110      * @param methodName   the name of the method to be called
111      * @param eventSource  the object which is generating events (JButton, JList, etc.)
112      * @param listenerType the listener interface (ActionListener.class, SelectionListener.class, etc.)
113      * @param eventTypes   the event types (method names) from the listener interface (if none specified, all will be
114      *                     supported)
115      */
116     public static <L> void bindEventsToMethod(final Object target, final String methodName, final Object eventSource,
117             final Class<L> listenerType, final String... eventTypes) {
118         final L listener = listenerType.cast(Proxy.newProxyInstance(target.getClass().getClassLoader(),
119                 new Class[] { listenerType }, new EventBindingInvocationHandler(target, methodName, eventTypes)));
120         addEventListener(eventSource, listenerType, listener);
121     }
122 
123     /**
124      * Make private in 4.0.
125      *
126      * @deprecated TODO Make private in 4.0.
127      */
128     @Deprecated
129     public EventUtils() {
130         // empty
131     }
132 }