PageRenderTime 99ms CodeModel.GetById 85ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/jEdit/tags/jedit-4-5-pre1/org/gjt/sp/jedit/bsh/XThis.java

#
Java | 201 lines | 87 code | 22 blank | 92 comment | 14 complexity | e07bd3575c041b4952f52f53e1d24439 MD5 | raw file
  1/*****************************************************************************
  2 *                                                                           *
  3 *  This file is part of the BeanShell Java Scripting distribution.          *
  4 *  Documentation and updates may be found at http://www.beanshell.org/      *
  5 *                                                                           *
  6 *  Sun Public License Notice:                                               *
  7 *                                                                           *
  8 *  The contents of this file are subject to the Sun Public License Version  *
  9 *  1.0 (the "License"); you may not use this file except in compliance with *
 10 *  the License. A copy of the License is available at http://www.sun.com    *
 11 *                                                                           *
 12 *  The Original Code is BeanShell. The Initial Developer of the Original    *
 13 *  Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright     *
 14 *  (C) 2000.  All Rights Reserved.                                          *
 15 *                                                                           *
 16 *  GNU Public License Notice:                                               *
 17 *                                                                           *
 18 *  Alternatively, the contents of this file may be used under the terms of  *
 19 *  the GNU Lesser General Public License (the "LGPL"), in which case the    *
 20 *  provisions of LGPL are applicable instead of those above. If you wish to *
 21 *  allow use of your version of this file only under the  terms of the LGPL *
 22 *  and not to allow others to use your version of this file under the SPL,  *
 23 *  indicate your decision by deleting the provisions above and replace      *
 24 *  them with the notice and other provisions required by the LGPL.  If you  *
 25 *  do not delete the provisions above, a recipient may use your version of  *
 26 *  this file under either the SPL or the LGPL.                              *
 27 *                                                                           *
 28 *  Patrick Niemeyer (pat@pat.net)                                           *
 29 *  Author of Learning Java, O'Reilly & Associates                           *
 30 *  http://www.pat.net/~pat/                                                 *
 31 *                                                                           *
 32 *****************************************************************************/
 33
 34
 35package org.gjt.sp.jedit.bsh;
 36
 37import java.lang.reflect.*;
 38import java.lang.reflect.InvocationHandler;
 39import java.util.Hashtable;
 40
 41/**
 42    XThis is a dynamically loaded extension which extends This.java and adds
 43    support for the generalized interface proxy mechanism introduced in
 44    JDK1.3.  XThis allows bsh scripted objects to implement arbitrary
 45    interfaces (be arbitrary event listener types).
 46
 47    Note: This module relies on new features of JDK1.3 and will not compile
 48    with JDK1.2 or lower.  For those environments simply do not compile this
 49    class.
 50
 51    Eventually XThis should become simply This, but for backward compatability
 52    we will maintain This without requiring support for the proxy mechanism.
 53
 54    XThis stands for "eXtended This" (I had to call it something).
 55
 56    @see org.gjt.sp.jedit.bsh.JThis	JThis
 57    See also JThis with explicit JFC support for compatability.
 58    @see org.gjt.sp.jedit.bsh.This This
 59*/
 60public class XThis extends This
 61    {
 62    /**
 63        A cache of proxy interface handlers.
 64        Currently just one per interface.
 65    */
 66    Hashtable interfaces;
 67
 68    InvocationHandler invocationHandler = new Handler();
 69
 70    public XThis( NameSpace namespace, Interpreter declaringInterp ) {
 71        super( namespace, declaringInterp );
 72    }
 73
 74    public String toString() {
 75        return "'this' reference (XThis) to Bsh object: " + namespace;
 76    }
 77
 78    /**
 79        Get dynamic proxy for interface, caching those it creates.
 80    */
 81    public Object getInterface( Class clas )
 82    {
 83        return getInterface( new Class[] { clas } );
 84    }
 85
 86    /**
 87        Get dynamic proxy for interface, caching those it creates.
 88    */
 89    public Object getInterface( Class [] ca )
 90    {
 91        if ( interfaces == null )
 92            interfaces = new Hashtable();
 93
 94        // Make a hash of the interface hashcodes in order to cache them
 95        int hash = 21;
 96        for(int i=0; i<ca.length; i++)
 97            hash *= ca[i].hashCode() + 3;
 98        Object hashKey = new Integer(hash);
 99
100        Object interf = interfaces.get( hashKey );
101
102        if ( interf == null )
103        {
104            ClassLoader classLoader = ca[0].getClassLoader(); // ?
105            interf = Proxy.newProxyInstance(
106                classLoader, ca, invocationHandler );
107            interfaces.put( hashKey, interf );
108        }
109
110        return interf;
111    }
112
113    /**
114        This is the invocation handler for the dynamic proxy.
115        <p>
116
117        Notes:
118        Inner class for the invocation handler seems to shield this unavailable
119        interface from JDK1.2 VM...
120
121        I don't understand this.  JThis works just fine even if those
122        classes aren't there (doesn't it?)  This class shouldn't be loaded
123        if an XThis isn't instantiated in NameSpace.java, should it?
124    */
125    class Handler implements InvocationHandler, java.io.Serializable
126    {
127        public Object invoke( Object proxy, Method method, Object[] args )
128            throws Throwable
129        {
130            try {
131                return invokeImpl( proxy, method, args );
132            } catch ( TargetError te ) {
133                // Unwrap target exception.  If the interface declares that
134                // it throws the ex it will be delivered.  If not it will be
135                // wrapped in an UndeclaredThrowable
136                throw te.getTarget();
137            } catch ( EvalError ee ) {
138                // Ease debugging...
139                // XThis.this refers to the enclosing class instance
140                if ( Interpreter.DEBUG )
141                    Interpreter.debug( "EvalError in scripted interface: "
142                    + XThis.this.toString() + ": "+ ee );
143                throw ee;
144            }
145        }
146
147        public Object invokeImpl( Object proxy, Method method, Object[] args )
148            throws EvalError
149        {
150            String methodName = method.getName();
151            CallStack callstack = new CallStack( namespace );
152
153            /*
154                If equals() is not explicitly defined we must override the
155                default implemented by the This object protocol for scripted
156                object.  To support XThis equals() must test for equality with
157                the generated proxy object, not the scripted bsh This object;
158                otherwise callers from outside in Java will not see a the
159                proxy object as equal to itself.
160            */
161            BshMethod equalsMethod = null;
162            try {
163                equalsMethod = namespace.getMethod(
164                    "equals", new Class [] { Object.class } );
165            } catch ( UtilEvalError e ) {/*leave null*/ }
166            if ( methodName.equals("equals" ) && equalsMethod == null ) {
167                Object obj = args[0];
168                return new Boolean( proxy == obj );
169            }
170
171            /*
172                If toString() is not explicitly defined override the default
173                to show the proxy interfaces.
174            */
175            BshMethod toStringMethod = null;
176            try {
177                toStringMethod =
178                    namespace.getMethod( "toString", new Class [] { } );
179            } catch ( UtilEvalError e ) {/*leave null*/ }
180
181            if ( methodName.equals("toString" ) && toStringMethod == null)
182            {
183                Class [] ints = proxy.getClass().getInterfaces();
184                // XThis.this refers to the enclosing class instance
185                StringBuilder sb = new StringBuilder(
186                    XThis.this.toString() + "\nimplements:" );
187                for(int i=0; i<ints.length; i++)
188                    sb.append( " "+ ints[i].getName()
189                        + ((ints.length > 1)?",":"") );
190                return sb.toString();
191            }
192
193            Class [] paramTypes = method.getParameterTypes();
194            return Primitive.unwrap(
195                invokeMethod( methodName, Primitive.wrap(args, paramTypes) ) );
196        }
197    };
198}
199
200
201