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    *      https://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.ObjectUtils;
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           * Tests 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 SecurityException Thrown if an underlying accessible object's method denies the request.
73           * @see SecurityManager#checkPermission
74           * @throws Throwable Thrown if an error occurs.
75           */
76          @Override
77          public Object invoke(final Object proxy, final Method method, final Object[] parameters) throws Throwable {
78              if (method.getDeclaringClass() == Object.class) {
79                  // Handle Object methods locally instead of dispatching them to the bound target,
80                  // mirroring java.beans.EventHandler: routine host actions (hash-based collections,
81                  // logging, equality checks during listener de-registration) must not invoke the
82                  // target method and must not return null into an unboxing context.
83                  switch (method.getName()) {
84                  case "hashCode":
85                      return Integer.valueOf(System.identityHashCode(proxy));
86                  case "equals":
87                      return Boolean.valueOf(proxy == parameters[0]);
88                  default: // toString
89                      return ObjectUtils.identityToString(proxy);
90                  }
91              }
92              if (eventTypes.isEmpty() || eventTypes.contains(method.getName())) {
93                  if (hasMatchingParametersMethod(method)) {
94                      return MethodUtils.invokeMethod(target, methodName, parameters);
95                  }
96                  return MethodUtils.invokeMethod(target, methodName);
97              }
98              return null;
99          }
100     }
101 
102     /**
103      * Adds an event listener to the specified source.  This looks for an "add" method corresponding to the event
104      * type (addActionListener, for example).
105      *
106      * @param eventSource   The event source.
107      * @param listenerType  The event listener type.
108      * @param listener      The listener.
109      * @param <L>           the event listener type.
110      * @throws IllegalArgumentException Thrown if the object doesn't support the listener type.
111      */
112     public static <L> void addEventListener(final Object eventSource, final Class<L> listenerType, final L listener) {
113         try {
114             MethodUtils.invokeMethod(eventSource, "add" + listenerType.getSimpleName(), listener);
115         } catch (final ReflectiveOperationException e) {
116             throw new IllegalArgumentException("Unable to add listener for class " + eventSource.getClass().getName()
117                     + " and public add" + listenerType.getSimpleName()
118                     + " method which takes a parameter of type " + listenerType.getName() + ".");
119         }
120     }
121 
122     /**
123      * Binds an event listener to a specific method on a specific object.
124      *
125      * @param <L>          the event listener type.
126      * @param target       The target object.
127      * @param methodName   The name of the method to be called.
128      * @param eventSource  The object which is generating events (JButton, JList, etc.).
129      * @param listenerType The listener interface (ActionListener.class, SelectionListener.class, etc.).
130      * @param eventTypes   The event types (method names) from the listener interface (if none specified, all will be
131      *                     supported).
132      */
133     public static <L> void bindEventsToMethod(final Object target, final String methodName, final Object eventSource,
134             final Class<L> listenerType, final String... eventTypes) {
135         final L listener = listenerType.cast(Proxy.newProxyInstance(target.getClass().getClassLoader(),
136                 new Class[] { listenerType }, new EventBindingInvocationHandler(target, methodName, eventTypes)));
137         addEventListener(eventSource, listenerType, listener);
138     }
139 
140     /**
141      * Make private in 4.0.
142      *
143      * @deprecated TODO Make private in 4.0.
144      */
145     @Deprecated
146     public EventUtils() {
147         // empty
148     }
149 }