1 33 34 35 package bsh; 36 37 import java.lang.reflect.*; 38 import java.lang.reflect.InvocationHandler ; 39 import java.io.*; 40 import java.util.Hashtable ; 41 42 60 public class XThis extends This 61 { 62 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 81 public Object getInterface( Class clas ) 82 { 83 return getInterface( new Class [] { clas } ); 84 } 85 86 89 public Object getInterface( Class [] ca ) 90 { 91 if ( interfaces == null ) 92 interfaces = new Hashtable (); 93 94 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(); interf = Proxy.newProxyInstance( 106 classLoader, ca, invocationHandler ); 107 interfaces.put( hashKey, interf ); 108 } 109 110 return interf; 111 } 112 113 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 throw te.getTarget(); 137 } catch ( EvalError ee ) { 138 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 161 BshMethod equalsMethod = null; 162 try { 163 equalsMethod = namespace.getMethod( 164 "equals", new Class [] { Object .class } ); 165 } catch ( UtilEvalError e ) { } 166 if ( methodName.equals("equals" ) && equalsMethod == null ) { 167 Object obj = args[0]; 168 return new Boolean ( proxy == obj ); 169 } 170 171 175 BshMethod toStringMethod = null; 176 try { 177 toStringMethod = 178 namespace.getMethod( "toString", new Class [] { } ); 179 } catch ( UtilEvalError e ) { } 180 181 if ( methodName.equals("toString" ) && toStringMethod == null) 182 { 183 Class [] ints = proxy.getClass().getInterfaces(); 184 StringBuffer sb = new StringBuffer ( 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 202 | Popular Tags |