/jEdit/branches/concurrency/org/gjt/sp/jedit/bsh/Reflect.java

# · Java · 967 lines · 598 code · 99 blank · 270 comment · 90 complexity · e887af2ca5adfa4a746c2b3c99dfa1e3 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. package org.gjt.sp.jedit.bsh;
  34. import java.lang.reflect.*;
  35. import java.util.Vector;
  36. /**
  37. All of the reflection API code lies here. It is in the form of static
  38. utilities. Maybe this belongs in LHS.java or a generic object
  39. wrapper class.
  40. */
  41. /*
  42. Note: This class is messy. The method and field resolution need to be
  43. rewritten. Various methods in here catch NoSuchMethod or NoSuchField
  44. exceptions during their searches. These should be rewritten to avoid
  45. having to catch the exceptions. Method lookups are now cached at a high
  46. level so they are less important, however the logic is messy.
  47. */
  48. class Reflect
  49. {
  50. /**
  51. Invoke method on arbitrary object instance.
  52. invocation may be static (through the object instance) or dynamic.
  53. Object may be a bsh scripted object (bsh.This type).
  54. @return the result of the method call
  55. */
  56. public static Object invokeObjectMethod(
  57. Object object, String methodName, Object[] args,
  58. Interpreter interpreter, CallStack callstack, SimpleNode callerInfo )
  59. throws ReflectError, EvalError, InvocationTargetException
  60. {
  61. // Bsh scripted object
  62. if ( object instanceof This && !This.isExposedThisMethod(methodName) )
  63. return ((This)object).invokeMethod(
  64. methodName, args, interpreter, callstack, callerInfo,
  65. false/*delcaredOnly*/
  66. );
  67. // Plain Java object, find the java method
  68. try {
  69. BshClassManager bcm =
  70. interpreter == null ? null : interpreter.getClassManager();
  71. Class clas = object.getClass();
  72. Method method = resolveExpectedJavaMethod(
  73. bcm, clas, object, methodName, args, false );
  74. return invokeMethod( method, object, args );
  75. } catch ( UtilEvalError e ) {
  76. throw e.toEvalError( callerInfo, callstack );
  77. }
  78. }
  79. /**
  80. Invoke a method known to be static.
  81. No object instance is needed and there is no possibility of the
  82. method being a bsh scripted method.
  83. */
  84. public static Object invokeStaticMethod(
  85. BshClassManager bcm, Class clas, String methodName, Object [] args )
  86. throws ReflectError, UtilEvalError, InvocationTargetException
  87. {
  88. Interpreter.debug("invoke static Method");
  89. Method method = resolveExpectedJavaMethod(
  90. bcm, clas, null, methodName, args, true );
  91. return invokeMethod( method, null, args );
  92. }
  93. /**
  94. Invoke the Java method on the specified object, performing needed
  95. type mappings on arguments and return values.
  96. @param args may be null
  97. */
  98. static Object invokeMethod(
  99. Method method, Object object, Object[] args )
  100. throws ReflectError, InvocationTargetException
  101. {
  102. if ( args == null )
  103. args = new Object[0];
  104. logInvokeMethod( "Invoking method (entry): ", method, args );
  105. // Map types to assignable forms, need to keep this fast...
  106. Object [] tmpArgs = new Object [ args.length ];
  107. Class [] types = method.getParameterTypes();
  108. try {
  109. for (int i=0; i<args.length; i++)
  110. tmpArgs[i] = Types.castObject(
  111. args[i]/*rhs*/, types[i]/*lhsType*/, Types.ASSIGNMENT );
  112. } catch ( UtilEvalError e ) {
  113. throw new InterpreterError(
  114. "illegal argument type in method invocation: "+e );
  115. }
  116. // unwrap any primitives
  117. tmpArgs = Primitive.unwrap( tmpArgs );
  118. logInvokeMethod( "Invoking method (after massaging values): ",
  119. method, tmpArgs );
  120. try {
  121. Object returnValue = method.invoke( object, tmpArgs );
  122. if ( returnValue == null )
  123. returnValue = Primitive.NULL;
  124. Class returnType = method.getReturnType();
  125. return Primitive.wrap( returnValue, returnType );
  126. } catch( IllegalAccessException e ) {
  127. throw new ReflectError( "Cannot access method "
  128. + StringUtil.methodString(
  129. method.getName(), method.getParameterTypes() )
  130. + " in '" + method.getDeclaringClass() + "' :" + e );
  131. }
  132. }
  133. public static Object getIndex(Object array, int index)
  134. throws ReflectError, UtilTargetError
  135. {
  136. if ( Interpreter.DEBUG )
  137. Interpreter.debug("getIndex: "+array+", index="+index);
  138. try {
  139. Object val = Array.get(array, index);
  140. return Primitive.wrap( val, array.getClass().getComponentType() );
  141. }
  142. catch( ArrayIndexOutOfBoundsException e1 ) {
  143. throw new UtilTargetError( e1 );
  144. } catch(Exception e) {
  145. throw new ReflectError("Array access:" + e);
  146. }
  147. }
  148. public static void setIndex(Object array, int index, Object val)
  149. throws ReflectError, UtilTargetError
  150. {
  151. try {
  152. val = Primitive.unwrap(val);
  153. Array.set(array, index, val);
  154. }
  155. catch( ArrayStoreException e2 ) {
  156. throw new UtilTargetError( e2 );
  157. } catch( IllegalArgumentException e1 ) {
  158. throw new UtilTargetError(
  159. new ArrayStoreException( e1.toString() ) );
  160. } catch(Exception e) {
  161. throw new ReflectError("Array access:" + e);
  162. }
  163. }
  164. public static Object getStaticFieldValue(Class clas, String fieldName)
  165. throws UtilEvalError, ReflectError
  166. {
  167. return getFieldValue( clas, null, fieldName, true/*onlystatic*/);
  168. }
  169. /**
  170. */
  171. public static Object getObjectFieldValue( Object object, String fieldName )
  172. throws UtilEvalError, ReflectError
  173. {
  174. if ( object instanceof This )
  175. return ((This)object).namespace.getVariable( fieldName );
  176. else {
  177. try {
  178. return getFieldValue(
  179. object.getClass(), object, fieldName, false/*onlystatic*/);
  180. } catch ( ReflectError e ) {
  181. // no field, try property acces
  182. if ( hasObjectPropertyGetter( object.getClass(), fieldName ) )
  183. return getObjectProperty( object, fieldName );
  184. else
  185. throw e;
  186. }
  187. }
  188. }
  189. static LHS getLHSStaticField(Class clas, String fieldName)
  190. throws UtilEvalError, ReflectError
  191. {
  192. Field f = resolveExpectedJavaField(
  193. clas, fieldName, true/*onlystatic*/);
  194. return new LHS(f);
  195. }
  196. /**
  197. Get an LHS reference to an object field.
  198. This method also deals with the field style property access.
  199. In the field does not exist we check for a property setter.
  200. */
  201. static LHS getLHSObjectField( Object object, String fieldName )
  202. throws UtilEvalError, ReflectError
  203. {
  204. if ( object instanceof This )
  205. {
  206. // I guess this is when we pass it as an argument?
  207. // Setting locally
  208. boolean recurse = false;
  209. return new LHS( ((This)object).namespace, fieldName, recurse );
  210. }
  211. try {
  212. Field f = resolveExpectedJavaField(
  213. object.getClass(), fieldName, false/*staticOnly*/ );
  214. return new LHS(object, f);
  215. } catch ( ReflectError e )
  216. {
  217. // not a field, try property access
  218. if ( hasObjectPropertySetter( object.getClass(), fieldName ) )
  219. return new LHS( object, fieldName );
  220. else
  221. throw e;
  222. }
  223. }
  224. private static Object getFieldValue(
  225. Class clas, Object object, String fieldName, boolean staticOnly )
  226. throws UtilEvalError, ReflectError
  227. {
  228. try {
  229. Field f = resolveExpectedJavaField( clas, fieldName, staticOnly );
  230. Object value = f.get(object);
  231. Class returnType = f.getType();
  232. return Primitive.wrap( value, returnType );
  233. } catch( NullPointerException e ) { // shouldn't happen
  234. throw new ReflectError(
  235. "???" + fieldName + " is not a static field.");
  236. } catch(IllegalAccessException e) {
  237. throw new ReflectError("Can't access field: " + fieldName);
  238. }
  239. }
  240. /*
  241. Note: this method and resolveExpectedJavaField should be rewritten
  242. to invert this logic so that no exceptions need to be caught
  243. unecessarily. This is just a temporary impl.
  244. @return the field or null if not found
  245. */
  246. protected static Field resolveJavaField(
  247. Class clas, String fieldName, boolean staticOnly )
  248. throws UtilEvalError
  249. {
  250. try {
  251. return resolveExpectedJavaField( clas, fieldName, staticOnly );
  252. } catch ( ReflectError e ) {
  253. return null;
  254. }
  255. }
  256. /**
  257. @throws ReflectError if the field is not found.
  258. */
  259. /*
  260. Note: this should really just throw NoSuchFieldException... need
  261. to change related signatures and code.
  262. */
  263. protected static Field resolveExpectedJavaField(
  264. Class clas, String fieldName, boolean staticOnly
  265. )
  266. throws UtilEvalError, ReflectError
  267. {
  268. Field field;
  269. try {
  270. if ( Capabilities.haveAccessibility() )
  271. field = findAccessibleField( clas, fieldName );
  272. else
  273. // Class getField() finds only public (and in interfaces, etc.)
  274. field = clas.getField(fieldName);
  275. }
  276. catch( NoSuchFieldException e) {
  277. throw new ReflectError("No such field: " + fieldName );
  278. } catch ( SecurityException e ) {
  279. throw new UtilTargetError(
  280. "Security Exception while searching fields of: "+clas,
  281. e );
  282. }
  283. if ( staticOnly && !Modifier.isStatic( field.getModifiers() ) )
  284. throw new UtilEvalError(
  285. "Can't reach instance field: "+fieldName
  286. +" from static context: "+clas.getName() );
  287. return field;
  288. }
  289. /**
  290. Used when accessibility capability is available to locate an occurrance
  291. of the field in the most derived class or superclass and set its
  292. accessibility flag.
  293. Note that this method is not needed in the simple non accessible
  294. case because we don't have to hunt for fields.
  295. Note that classes may declare overlapping private fields, so the
  296. distinction about the most derived is important. Java doesn't normally
  297. allow this kind of access (super won't show private variables) so
  298. there is no real syntax for specifying which class scope to use...
  299. @return the Field or throws NoSuchFieldException
  300. @throws NoSuchFieldException if the field is not found
  301. */
  302. /*
  303. This method should be rewritten to use getFields() and avoid catching
  304. exceptions during the search.
  305. */
  306. private static Field findAccessibleField( Class clas, String fieldName )
  307. throws UtilEvalError, NoSuchFieldException
  308. {
  309. Field field;
  310. // Quick check catches public fields include those in interfaces
  311. try {
  312. field = clas.getField(fieldName);
  313. ReflectManager.RMSetAccessible( field );
  314. return field;
  315. } catch ( NoSuchFieldException e ) { }
  316. // Now, on with the hunt...
  317. while ( clas != null )
  318. {
  319. try {
  320. field = clas.getDeclaredField(fieldName);
  321. ReflectManager.RMSetAccessible( field );
  322. return field;
  323. // Not found, fall through to next class
  324. } catch(NoSuchFieldException e) { }
  325. clas = clas.getSuperclass();
  326. }
  327. throw new NoSuchFieldException( fieldName );
  328. }
  329. /**
  330. This method wraps resolveJavaMethod() and expects a non-null method
  331. result. If the method is not found it throws a descriptive ReflectError.
  332. */
  333. protected static Method resolveExpectedJavaMethod(
  334. BshClassManager bcm, Class clas, Object object,
  335. String name, Object[] args, boolean staticOnly )
  336. throws ReflectError, UtilEvalError
  337. {
  338. if ( object == Primitive.NULL )
  339. throw new UtilTargetError( new NullPointerException(
  340. "Attempt to invoke method " +name+" on null value" ) );
  341. Class [] types = Types.getTypes(args);
  342. Method method = resolveJavaMethod( bcm, clas, name, types, staticOnly );
  343. if ( method == null )
  344. throw new ReflectError(
  345. ( staticOnly ? "Static method " : "Method " )
  346. + StringUtil.methodString(name, types) +
  347. " not found in class'" + clas.getName() + "'");
  348. return method;
  349. }
  350. /**
  351. The full blown resolver method. All other method invocation methods
  352. delegate to this. The method may be static or dynamic unless
  353. staticOnly is set (in which case object may be null).
  354. If staticOnly is set then only static methods will be located.
  355. <p/>
  356. This method performs caching (caches discovered methods through the
  357. class manager and utilizes cached methods.)
  358. <p/>
  359. This method determines whether to attempt to use non-public methods
  360. based on Capabilities.haveAccessibility() and will set the accessibilty
  361. flag on the method as necessary.
  362. <p/>
  363. If, when directed to find a static method, this method locates a more
  364. specific matching instance method it will throw a descriptive exception
  365. analogous to the error that the Java compiler would produce.
  366. Note: as of 2.0.x this is a problem because there is no way to work
  367. around this with a cast.
  368. <p/>
  369. @param staticOnly
  370. The method located must be static, the object param may be null.
  371. @return the method or null if no matching method was found.
  372. */
  373. protected static Method resolveJavaMethod(
  374. BshClassManager bcm, Class clas, String name,
  375. Class [] types, boolean staticOnly )
  376. throws UtilEvalError
  377. {
  378. if ( clas == null )
  379. throw new InterpreterError("null class");
  380. // Lookup previously cached method
  381. Method method = null;
  382. if ( bcm == null )
  383. Interpreter.debug("resolveJavaMethod UNOPTIMIZED lookup");
  384. else
  385. method = bcm.getResolvedMethod( clas, name, types, staticOnly );
  386. if ( method == null )
  387. {
  388. boolean publicOnly = !Capabilities.haveAccessibility();
  389. // Searching for the method may, itself be a priviledged action
  390. try {
  391. method = findOverloadedMethod( clas, name, types, publicOnly );
  392. } catch ( SecurityException e ) {
  393. throw new UtilTargetError(
  394. "Security Exception while searching methods of: "+clas,
  395. e );
  396. }
  397. checkFoundStaticMethod( method, staticOnly, clas );
  398. // This is the first time we've seen this method, set accessibility
  399. // Note: even if it's a public method, we may have found it in a
  400. // non-public class
  401. if ( method != null && !publicOnly ) {
  402. try {
  403. ReflectManager.RMSetAccessible( method );
  404. } catch ( UtilEvalError e ) { /*ignore*/ }
  405. }
  406. // If succeeded cache the resolved method.
  407. if ( method != null && bcm != null )
  408. bcm.cacheResolvedMethod( clas, types, method );
  409. }
  410. return method;
  411. }
  412. /**
  413. Get the candidate methods by searching the class and interface graph
  414. of baseClass and resolve the most specific.
  415. @return the method or null for not found
  416. */
  417. private static Method findOverloadedMethod(
  418. Class baseClass, String methodName, Class[] types, boolean publicOnly )
  419. {
  420. if ( Interpreter.DEBUG )
  421. Interpreter.debug( "Searching for method: "+
  422. StringUtil.methodString(methodName, types)
  423. + " in '" + baseClass.getName() + "'" );
  424. Method [] methods = getCandidateMethods(
  425. baseClass, methodName, types.length, publicOnly );
  426. if ( Interpreter.DEBUG )
  427. Interpreter.debug("Looking for most specific method: "+methodName);
  428. Method method = findMostSpecificMethod( types, methods );
  429. return method;
  430. }
  431. /**
  432. Climb the class and interface inheritence graph of the type and collect
  433. all methods matching the specified name and criterion. If publicOnly
  434. is true then only public methods in *public* classes or interfaces will
  435. be returned. In the normal (non-accessible) case this addresses the
  436. problem that arises when a package private class or private inner class
  437. implements a public interface or derives from a public type.
  438. <p/>
  439. This method primarily just delegates to gatherMethodsRecursive()
  440. @see #gatherMethodsRecursive(
  441. Class, String, int, boolean, java.util.Vector)
  442. */
  443. static Method[] getCandidateMethods(
  444. Class baseClass, String methodName, int numArgs,
  445. boolean publicOnly )
  446. {
  447. Vector candidates = gatherMethodsRecursive(
  448. baseClass, methodName, numArgs, publicOnly, null/*candidates*/);
  449. // return the methods in an array
  450. Method [] ma = new Method[ candidates.size() ];
  451. candidates.copyInto( ma );
  452. return ma;
  453. }
  454. /**
  455. Accumulate all methods, optionally including non-public methods,
  456. class and interface, in the inheritence tree of baseClass.
  457. This method is analogous to Class getMethods() which returns all public
  458. methods in the inheritence tree.
  459. In the normal (non-accessible) case this also addresses the problem
  460. that arises when a package private class or private inner class
  461. implements a public interface or derives from a public type. In other
  462. words, sometimes we'll find public methods that we can't use directly
  463. and we have to find the same public method in a parent class or
  464. interface.
  465. @return the candidate methods vector
  466. */
  467. private static Vector gatherMethodsRecursive(
  468. Class baseClass, String methodName, int numArgs,
  469. boolean publicOnly, Vector candidates )
  470. {
  471. if ( candidates == null )
  472. candidates = new Vector();
  473. // Add methods of the current class to the vector.
  474. // In public case be careful to only add methods from a public class
  475. // and to use getMethods() instead of getDeclaredMethods()
  476. // (This addresses secure environments)
  477. if ( publicOnly ) {
  478. if ( isPublic(baseClass) )
  479. addCandidates( baseClass.getMethods(),
  480. methodName, numArgs, publicOnly, candidates );
  481. } else
  482. addCandidates( baseClass.getDeclaredMethods(),
  483. methodName, numArgs, publicOnly, candidates );
  484. // Does the class or interface implement interfaces?
  485. Class [] intfs = baseClass.getInterfaces();
  486. for( int i=0; i< intfs.length; i++ )
  487. gatherMethodsRecursive( intfs[i],
  488. methodName, numArgs, publicOnly, candidates );
  489. // Do we have a superclass? (interfaces don't, etc.)
  490. Class superclass = baseClass.getSuperclass();
  491. if ( superclass != null )
  492. gatherMethodsRecursive( superclass,
  493. methodName, numArgs, publicOnly, candidates );
  494. return candidates;
  495. }
  496. private static Vector addCandidates(
  497. Method [] methods, String methodName,
  498. int numArgs, boolean publicOnly, Vector candidates )
  499. {
  500. for ( int i = 0; i < methods.length; i++ )
  501. {
  502. Method m = methods[i];
  503. if ( m.getName().equals( methodName )
  504. && ( m.getParameterTypes().length == numArgs )
  505. && ( !publicOnly || isPublic( m ) )
  506. )
  507. candidates.add( m );
  508. }
  509. return candidates;
  510. }
  511. /**
  512. Primary object constructor
  513. This method is simpler than those that must resolve general method
  514. invocation because constructors are not inherited.
  515. <p/>
  516. This method determines whether to attempt to use non-public constructors
  517. based on Capabilities.haveAccessibility() and will set the accessibilty
  518. flag on the method as necessary.
  519. <p/>
  520. */
  521. static Object constructObject( Class clas, Object[] args )
  522. throws ReflectError, InvocationTargetException
  523. {
  524. if ( clas.isInterface() )
  525. throw new ReflectError(
  526. "Can't create instance of an interface: "+clas);
  527. Object obj = null;
  528. Class[] types = Types.getTypes(args);
  529. Constructor con = null;
  530. // Find the constructor.
  531. // (there are no inherited constructors to worry about)
  532. Constructor[] constructors =
  533. Capabilities.haveAccessibility() ?
  534. clas.getDeclaredConstructors() : clas.getConstructors() ;
  535. if ( Interpreter.DEBUG )
  536. Interpreter.debug("Looking for most specific constructor: "+clas);
  537. con = findMostSpecificConstructor(types, constructors);
  538. if ( con == null )
  539. throw cantFindConstructor( clas, types );
  540. if ( !isPublic( con ) )
  541. try {
  542. ReflectManager.RMSetAccessible( con );
  543. } catch ( UtilEvalError e ) { /*ignore*/ }
  544. args=Primitive.unwrap( args );
  545. try {
  546. obj = con.newInstance( args );
  547. } catch(InstantiationException e) {
  548. throw new ReflectError("The class "+clas+" is abstract ");
  549. } catch(IllegalAccessException e) {
  550. throw new ReflectError(
  551. "We don't have permission to create an instance."
  552. +"Use setAccessibility(true) to enable access." );
  553. } catch(IllegalArgumentException e) {
  554. throw new ReflectError("The number of arguments was wrong");
  555. }
  556. if (obj == null)
  557. throw new ReflectError("Couldn't construct the object");
  558. return obj;
  559. }
  560. /*
  561. This method should parallel findMostSpecificMethod()
  562. The only reason it can't be combined is that Method and Constructor
  563. don't have a common interface for their signatures
  564. */
  565. static Constructor findMostSpecificConstructor(
  566. Class[] idealMatch, Constructor[] constructors)
  567. {
  568. int match = findMostSpecificConstructorIndex(idealMatch, constructors );
  569. return ( match == -1 ) ? null : constructors[ match ];
  570. }
  571. static int findMostSpecificConstructorIndex(
  572. Class[] idealMatch, Constructor[] constructors)
  573. {
  574. Class [][] candidates = new Class [ constructors.length ] [];
  575. for(int i=0; i< candidates.length; i++ )
  576. candidates[i] = constructors[i].getParameterTypes();
  577. return findMostSpecificSignature( idealMatch, candidates );
  578. }
  579. /**
  580. Find the best match for signature idealMatch.
  581. It is assumed that the methods array holds only valid candidates
  582. (e.g. method name and number of args already matched).
  583. This method currently does not take into account Java 5 covariant
  584. return types... which I think will require that we find the most
  585. derived return type of otherwise identical best matches.
  586. @see #findMostSpecificSignature(Class[], Class[][])
  587. @param methods the set of candidate method which differ only in the
  588. types of their arguments.
  589. */
  590. static Method findMostSpecificMethod(
  591. Class[] idealMatch, Method[] methods )
  592. {
  593. // copy signatures into array for findMostSpecificMethod()
  594. Class [][] candidateSigs = new Class [ methods.length ][];
  595. for(int i=0; i<methods.length; i++)
  596. candidateSigs[i] = methods[i].getParameterTypes();
  597. int match = findMostSpecificSignature( idealMatch, candidateSigs );
  598. return match == -1 ? null : methods[match];
  599. }
  600. /**
  601. Implement JLS 15.11.2
  602. Return the index of the most specific arguments match or -1 if no
  603. match is found.
  604. This method is used by both methods and constructors (which
  605. unfortunately don't share a common interface for signature info).
  606. @return the index of the most specific candidate
  607. */
  608. /*
  609. Note: Two methods which are equally specific should not be allowed by
  610. the Java compiler. In this case BeanShell currently chooses the first
  611. one it finds. We could add a test for this case here (I believe) by
  612. adding another isSignatureAssignable() in the other direction between
  613. the target and "best" match. If the assignment works both ways then
  614. neither is more specific and they are ambiguous. I'll leave this test
  615. out for now because I'm not sure how much another test would impact
  616. performance. Method selection is now cached at a high level, so a few
  617. friendly extraneous tests shouldn't be a problem.
  618. */
  619. static int findMostSpecificSignature(
  620. Class [] idealMatch, Class [][] candidates )
  621. {
  622. for ( int round = Types.FIRST_ROUND_ASSIGNABLE;
  623. round <= Types.LAST_ROUND_ASSIGNABLE; round++ )
  624. {
  625. Class [] bestMatch = null;
  626. int bestMatchIndex = -1;
  627. for (int i=0; i < candidates.length; i++)
  628. {
  629. Class[] targetMatch = candidates[i];
  630. // If idealMatch fits targetMatch and this is the first match
  631. // or targetMatch is more specific than the best match, make it
  632. // the new best match.
  633. if ( Types.isSignatureAssignable(
  634. idealMatch, targetMatch, round )
  635. && ( (bestMatch == null) ||
  636. Types.isSignatureAssignable( targetMatch, bestMatch,
  637. Types.JAVA_BASE_ASSIGNABLE )
  638. )
  639. )
  640. {
  641. bestMatch = targetMatch;
  642. bestMatchIndex = i;
  643. }
  644. }
  645. if ( bestMatch != null )
  646. return bestMatchIndex;
  647. }
  648. return -1;
  649. }
  650. private static String accessorName( String getorset, String propName ) {
  651. return getorset
  652. + String.valueOf(Character.toUpperCase(propName.charAt(0)))
  653. + propName.substring(1);
  654. }
  655. public static boolean hasObjectPropertyGetter(
  656. Class clas, String propName )
  657. {
  658. String getterName = accessorName("get", propName );
  659. try {
  660. clas.getMethod( getterName, new Class [0] );
  661. return true;
  662. } catch ( NoSuchMethodException e ) { /* fall through */ }
  663. getterName = accessorName("is", propName );
  664. try {
  665. Method m = clas.getMethod( getterName, new Class [0] );
  666. return ( m.getReturnType() == Boolean.TYPE );
  667. } catch ( NoSuchMethodException e ) {
  668. return false;
  669. }
  670. }
  671. public static boolean hasObjectPropertySetter(
  672. Class clas, String propName )
  673. {
  674. String setterName = accessorName("set", propName );
  675. Method [] methods = clas.getMethods();
  676. // we don't know the right hand side of the assignment yet.
  677. // has at least one setter of the right name?
  678. for(int i=0; i<methods.length; i++)
  679. if ( methods[i].getName().equals( setterName ) )
  680. return true;
  681. return false;
  682. }
  683. public static Object getObjectProperty(
  684. Object obj, String propName )
  685. throws UtilEvalError, ReflectError
  686. {
  687. Object[] args = new Object[] { };
  688. Interpreter.debug("property access: ");
  689. Method method = null;
  690. Exception e1=null, e2=null;
  691. try {
  692. String accessorName = accessorName( "get", propName );
  693. method = resolveExpectedJavaMethod(
  694. null/*bcm*/, obj.getClass(), obj, accessorName, args, false );
  695. } catch ( Exception e ) {
  696. e1 = e;
  697. }
  698. if ( method == null )
  699. try {
  700. String accessorName = accessorName( "is", propName );
  701. method = resolveExpectedJavaMethod(
  702. null/*bcm*/, obj.getClass(), obj,
  703. accessorName, args, false );
  704. if ( method.getReturnType() != Boolean.TYPE )
  705. method = null;
  706. } catch ( Exception e ) {
  707. e2 = e;
  708. }
  709. if ( method == null )
  710. throw new ReflectError("Error in property getter: "
  711. +e1 + (e2!=null?" : "+e2:"") );
  712. try {
  713. return invokeMethod( method, obj, args );
  714. }
  715. catch(InvocationTargetException e)
  716. {
  717. throw new UtilEvalError("Property accessor threw exception: "
  718. +e.getTargetException() );
  719. }
  720. }
  721. public static void setObjectProperty(
  722. Object obj, String propName, Object value)
  723. throws ReflectError, UtilEvalError
  724. {
  725. String accessorName = accessorName( "set", propName );
  726. Object[] args = new Object[] { value };
  727. Interpreter.debug("property access: ");
  728. try {
  729. Method method = resolveExpectedJavaMethod(
  730. null/*bcm*/, obj.getClass(), obj, accessorName, args, false );
  731. invokeMethod( method, obj, args );
  732. }
  733. catch ( InvocationTargetException e )
  734. {
  735. throw new UtilEvalError("Property accessor threw exception: "
  736. +e.getTargetException() );
  737. }
  738. }
  739. /**
  740. Return a more human readable version of the type name.
  741. Specifically, array types are returned with postfix "[]" dimensions.
  742. e.g. return "int []" for integer array instead of "class [I" as
  743. would be returned by Class getName() in that case.
  744. */
  745. public static String normalizeClassName(Class type)
  746. {
  747. if ( !type.isArray() )
  748. return type.getName();
  749. StringBuffer className = new StringBuffer();
  750. try {
  751. className.append( getArrayBaseType(type).getName() +" ");
  752. for(int i = 0; i < getArrayDimensions(type); i++)
  753. className.append("[]");
  754. } catch( ReflectError e ) { /*shouldn't happen*/ }
  755. return className.toString();
  756. }
  757. /**
  758. returns the dimensionality of the Class
  759. returns 0 if the Class is not an array class
  760. */
  761. public static int getArrayDimensions(Class arrayClass)
  762. {
  763. if ( !arrayClass.isArray() )
  764. return 0;
  765. return arrayClass.getName().lastIndexOf('[') + 1; // why so cute?
  766. }
  767. /**
  768. Returns the base type of an array Class.
  769. throws ReflectError if the Class is not an array class.
  770. */
  771. public static Class getArrayBaseType(Class arrayClass) throws ReflectError
  772. {
  773. if ( !arrayClass.isArray() )
  774. throw new ReflectError("The class is not an array.");
  775. return arrayClass.getComponentType();
  776. }
  777. /**
  778. A command may be implemented as a compiled Java class containing one or
  779. more static invoke() methods of the correct signature. The invoke()
  780. methods must accept two additional leading arguments of the interpreter
  781. and callstack, respectively. e.g. invoke(interpreter, callstack, ... )
  782. This method adds the arguments and invokes the static method, returning
  783. the result.
  784. */
  785. public static Object invokeCompiledCommand(
  786. Class commandClass, Object [] args, Interpreter interpreter,
  787. CallStack callstack )
  788. throws UtilEvalError
  789. {
  790. // add interpereter and namespace to args list
  791. Object[] invokeArgs = new Object[args.length + 2];
  792. invokeArgs[0] = interpreter;
  793. invokeArgs[1] = callstack;
  794. System.arraycopy( args, 0, invokeArgs, 2, args.length );
  795. BshClassManager bcm = interpreter.getClassManager();
  796. try {
  797. return Reflect.invokeStaticMethod(
  798. bcm, commandClass, "invoke", invokeArgs );
  799. } catch ( InvocationTargetException e ) {
  800. throw new UtilEvalError(
  801. "Error in compiled command: "+e.getTargetException() );
  802. } catch ( ReflectError e ) {
  803. throw new UtilEvalError("Error invoking compiled command: "+e );
  804. }
  805. }
  806. private static void logInvokeMethod(
  807. String msg, Method method, Object[] args )
  808. {
  809. if ( Interpreter.DEBUG )
  810. {
  811. Interpreter.debug( msg +method+" with args:" );
  812. for(int i=0; i<args.length; i++)
  813. Interpreter.debug(
  814. "args["+i+"] = "+args[i]
  815. +" type = "+args[i].getClass() );
  816. }
  817. }
  818. private static void checkFoundStaticMethod(
  819. Method method, boolean staticOnly, Class clas )
  820. throws UtilEvalError
  821. {
  822. // We're looking for a static method but found an instance method
  823. if ( method != null && staticOnly && !isStatic( method ) )
  824. throw new UtilEvalError(
  825. "Cannot reach instance method: "
  826. + StringUtil.methodString(
  827. method.getName(), method.getParameterTypes() )
  828. + " from static context: "+ clas.getName() );
  829. }
  830. private static ReflectError cantFindConstructor(
  831. Class clas, Class [] types )
  832. {
  833. if ( types.length == 0 )
  834. return new ReflectError(
  835. "Can't find default constructor for: "+clas);
  836. else
  837. return new ReflectError(
  838. "Can't find constructor: "
  839. + StringUtil.methodString( clas.getName(), types )
  840. +" in class: "+ clas.getName() );
  841. }
  842. private static boolean isPublic( Class c ) {
  843. return Modifier.isPublic( c.getModifiers() );
  844. }
  845. private static boolean isPublic( Method m ) {
  846. return Modifier.isPublic( m.getModifiers() );
  847. }
  848. private static boolean isPublic( Constructor c ) {
  849. return Modifier.isPublic( c.getModifiers() );
  850. }
  851. private static boolean isStatic( Method m ) {
  852. return Modifier.isStatic( m.getModifiers() );
  853. }
  854. }