⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 eventhandler.java

📁 gcc的组建
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* java.beans.EventHandler   Copyright (C) 2004, 2005 Free Software Foundation, Inc.This file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version. GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING.  If not, write to theFree Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA02110-1301 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library.  Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule.  An independent module is a module which is not derived fromor based on this library.  If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so.  If you do not wish to do so, delete thisexception statement from your version. */package java.beans;import java.lang.reflect.InvocationHandler;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.Proxy;/** * <p>EventHandler forms a bridge between dynamically created listeners and * arbitrary properties and methods.</p> *  * <p>You can use this class to easily create listener implementations for * some basic interactions between an event source and its target. Using * the three static methods named <code>create</code> you can create * these listener implementations.</p> *  * <p>See the documentation of each method for usage examples.</p> *   * @author Jerry Quinn (jlquinn@optonline.net) * @author Robert Schuster (thebohemian@gmx.net) * @since 1.4 */public class EventHandler implements InvocationHandler{  // The name of the method that will be implemented.  If null, any method.  private String listenerMethod;  // The object to call action on.  private Object target;  // The name of the method or property setter in target.  private String action;  // The property to extract from an event passed to listenerMethod.  private String property;  // The target objects Class.  private Class targetClass;    // String class doesn't already have a capitalize routine.  private String capitalize(String s)  {    return s.substring(0, 1).toUpperCase() + s.substring(1);  }  /**   * Creates a new <code>EventHandler</code> instance.   *   * <p>Typical creation is done with the create method, not by knewing an   * EventHandler.</p>   *   * <p>This constructs an EventHandler that will connect the method   * listenerMethodName to target.action, extracting eventPropertyName from   * the first argument of listenerMethodName. and sending it to action.</p>   *    * <p>Throws a <code>NullPointerException</code> if the <code>target</code>   * argument is <code>null</code>.    *   * @param target Object that will perform the action.   * @param action A property or method of the target.   * @param eventPropertyName A readable property of the inbound event.   * @param listenerMethodName The listener method name triggering the action.   */  public EventHandler(Object target, String action, String eventPropertyName,		      String listenerMethodName)  {    this.target = target;        // Retrieving the class is done for two reasons:    // 1) The class object is needed very frequently in the invoke() method.    // 2) The constructor should throw a NullPointerException if target is null.    targetClass = target.getClass();        this.action = action;	// Turn this into a method or do we wait till    		// runtime    property = eventPropertyName;    listenerMethod = listenerMethodName;  }  /**   * Returns the event property name.   */  public String getEventPropertyName()  {    return property;  }  /**   * Returns the listener's method name.   */  public String getListenerMethodName()  {    return listenerMethod;  }  /**   * Returns the target object.   */  public Object getTarget()  {    return target;  }  /**   * Returns the action method name.   */  public String getAction()  {    return action;  }  // Fetch a qualified property like a.b.c from object o.  The properties can  // be boolean isProp or object getProp properties.  //  // Returns a length 2 array with the first entry containing the value  // extracted from the property, and the second entry contains the class of  // the method return type.  //  // We play this game because if the method returns a native type, the return  // value will be a wrapper.  If we then take the type of the wrapper and use  // it to locate the action method that takes the native type, it won't match.  private Object[] getProperty(Object o, String prop)  {    // Isolate the first property name from a.b.c.    int pos;    String rest = null;    if ((pos = prop.indexOf('.')) != -1)      {	rest = prop.substring(pos + 1);	prop = prop.substring(0, pos);      }    // Find a method named getProp.  It could be isProp instead.    Method getter;    try      {	// Look for boolean property getter isProperty	getter = o.getClass().getMethod("is" + capitalize(prop),						 null);      }    catch (NoSuchMethodException nsme1)      {        try {          // Look for regular property getter getProperty          getter = o.getClass().getMethod("get" + capitalize(prop),						 null);        } catch(NoSuchMethodException nsme2) {            try {            // Finally look for a method of the name prop            getter = o.getClass().getMethod(prop, null);            } catch(NoSuchMethodException nsme3) {                // Ok, give up with an intelligent hint for the user.                throw new RuntimeException("Method not called: Could not find a property or method '" + prop                        + "' in " + o.getClass() + " while following the property argument '" + property + "'.");            }        }      }    try {      Object val = getter.invoke(o, null);      if (rest != null)        return getProperty(val, rest);      return new Object[] {val, getter.getReturnType()};    } catch(InvocationTargetException ite) {        throw new RuntimeException("Method not called: Property or method '" + prop + "' has thrown an exception.", ite);    } catch(IllegalAccessException iae) {        // This cannot happen because we looked up method with Class.getMethod()        // which returns public methods only.        throw (InternalError) new InternalError("Non-public method was invoked.").initCause(iae);    }  }  /**   * Invokes the <code>EventHandler</code>.   *    * <p>This method is normally called by the listener's proxy implementation.</p>   *    * @param proxy The listener interface that is implemented using   * the proxy mechanism.   * @param method The method that was called on the proxy instance.   * @param arguments The arguments which where given to the method.   * @throws Throwable <code>NoSuchMethodException</code> is thrown when the EventHandler's   * action method or property cannot be found.   */  public Object invoke(Object proxy, Method method, Object[] arguments)  {      try {      // The method instance of the target object. We have to find out which      // one we have to invoke.      Method actionMethod = null;    // Listener methods that weren't specified are ignored.  If listenerMethod    // is null, then all listener methods are processed.    if (listenerMethod != null && !method.getName().equals(listenerMethod))      return null;    // If a property is defined we definitely need a valid object at    // arguments[0] that can be used to retrieve a value to which the    // property of the target gets set.    if(property != null) {      // Extracts the argument. We will let it fail with a NullPointerException      // the caller used a listener method that has no arguments.      Object event = arguments[0];      // Obtains the property XXX propertyType keeps showing up null - why?      // because the object inside getProperty changes, but the ref variable      // can't change this way, dolt!  need a better way to get both values out      // - need method and object to do the invoke and get return type      Object v[] = getProperty(event, property);      Object[] args = new Object[] { v[0] };            // Changes the class array that controls which method signature we are going      // to look up in the target object.      Class[] argTypes = new Class[] { initClass((Class) v[1]) };          // Tries to  find a setter method to which we can apply the      while(argTypes[0] != null) {      try      {        // Look for a property setter for action.        actionMethod = targetClass.getMethod("set" + capitalize(action), argTypes);        return actionMethod.invoke(target, args);      }    catch (NoSuchMethodException e)      {        // If action as property didn't work, try as method later.      }          argTypes[0] = nextClass(argTypes[0]);      }            // We could not find a suitable setter method. Now we try again interpreting      // action as the method name itself.      // Since we probably have changed the block local argTypes array       // we need to rebuild it.      argTypes = new Class[] { initClass((Class) v[1]) };          // Tries to  find a setter method to which we can apply the      while(argTypes[0] != null) {        try        {          actionMethod = targetClass.getMethod(action, argTypes);          return actionMethod.invoke(target, args);        }        catch (NoSuchMethodException e)        {        }                argTypes[0] = nextClass(argTypes[0]);      }                throw new RuntimeException("Method not called: Could not find a public method named '"                + action + "' in target " + targetClass + " which takes a '"                + v[1] + "' argument or a property of this type.");      }            // If property was null we will search for a no-argument method here.    // Note: The ordering of method lookups is important because we want to prefer no-argument    // calls like the JDK does. This means if we have actionMethod() and actionMethod(Event) we will    // call the first *EVEN* if we have a valid argument for the second method. This is behavior compliant    // to the JDK.    // If actionMethod() is not available but there is a actionMethod(Event) we take this. That makes us    // more specification compliant than the JDK itself because this one will fail in such a case.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -