1. /*
  2. * @(#)Statement.java 1.18 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.beans;
  8. import java.lang.reflect.*;
  9. import java.util.*;
  10. /**
  11. * A <code>Statement</code> object represents a primitive statement
  12. * in which a single method is applied to a target and
  13. * a set of arguments - as in <code>"a.setFoo(b)"</code>.
  14. * Note that where this example uses names
  15. * to denote the target and its argument, a statement
  16. * object does not require a name space and is constructed with
  17. * the values themselves.
  18. * The statement object associates the named method
  19. * with its environment as a simple set of values:
  20. * the target and an array of argument values.
  21. *
  22. * @since 1.4
  23. *
  24. * @version 1.18 01/23/03
  25. * @author Philip Milne
  26. */
  27. public class Statement {
  28. private static Object[] emptyArray = new Object[]{};
  29. private static HashMap methodCache = null;
  30. static ExceptionListener defaultExceptionListener = new ExceptionListener() {
  31. public void exceptionThrown(Exception e) {
  32. System.err.println(e);
  33. // e.printStackTrace();
  34. System.err.println("Continuing ...");
  35. }
  36. };
  37. Object target;
  38. String methodName;
  39. Object[] arguments;
  40. /**
  41. * Creates a new <code>Statement</code> object with a <code>target</code>,
  42. * <code>methodName</code> and <code>arguments</code> as per the parameters.
  43. *
  44. * @param target The target of this statement.
  45. * @param methodName The methodName of this statement.
  46. * @param arguments The arguments of this statement.
  47. *
  48. */
  49. public Statement(Object target, String methodName, Object[] arguments) {
  50. this.target = target;
  51. this.methodName = methodName;
  52. this.arguments = (arguments == null) ? emptyArray : arguments;
  53. }
  54. /**
  55. * Returns the target of this statement.
  56. *
  57. * @return The target of this statement.
  58. */
  59. public Object getTarget() {
  60. return target;
  61. }
  62. /**
  63. * Returns the name of the method.
  64. *
  65. * @return The name of the method.
  66. */
  67. public String getMethodName() {
  68. return methodName;
  69. }
  70. /**
  71. * Returns the arguments of this statement.
  72. *
  73. * @return the arguments of this statement.
  74. */
  75. public Object[] getArguments() {
  76. return arguments;
  77. }
  78. /**
  79. * The execute method finds a method whose name is the same
  80. * as the methodName property, and invokes the method on
  81. * the target.
  82. *
  83. * When the target's class defines many methods with the given name
  84. * the implementation should choose the most specific method using
  85. * the algorithm specified in the Java Language Specification
  86. * (15.11). The dynamic class of the target and arguments are used
  87. * in place of the compile-time type information and, like the
  88. * <code>java.lang.reflect.Method</code> class itself, conversion between
  89. * primitive values and their associated wrapper classes is handled
  90. * internally.
  91. * <p>
  92. * The following method types are handled as special cases:
  93. * <ul>
  94. * <li>
  95. * Static methods may be called by using a class object as the target.
  96. * <li>
  97. * The reserved method name "new" may be used to call a class's constructor
  98. * as if all classes defined static "new" methods. Constructor invocations
  99. * are typically considered <code>Expression</code>s rather than <code>Statement</code>s
  100. * as they return a value.
  101. * <li>
  102. * The method names "get" and "set" defined in the <code>java.util.List</code>
  103. * interface may also be applied to array instances, mapping to
  104. * the static methods of the same name in the <code>Array</code> class.
  105. * </ul>
  106. */
  107. public void execute() throws Exception {
  108. invoke();
  109. }
  110. /*pp*/ static Class typeToClass(Class type) {
  111. return type.isPrimitive() ? typeNameToClass(type.getName()) : type;
  112. }
  113. /*pp*/ static Class typeNameToClass(String typeName) {
  114. typeName = typeName.intern();
  115. if (typeName == "boolean") return Boolean.class;
  116. if (typeName == "byte") return Byte.class;
  117. if (typeName == "char") return Character.class;
  118. if (typeName == "short") return Short.class;
  119. if (typeName == "int") return Integer.class;
  120. if (typeName == "long") return Long.class;
  121. if (typeName == "float") return Float.class;
  122. if (typeName == "double") return Double.class;
  123. if (typeName == "void") return Void.class;
  124. return null;
  125. }
  126. private static Class typeNameToPrimitiveClass(String typeName) {
  127. typeName = typeName.intern();
  128. if (typeName == "boolean") return boolean.class;
  129. if (typeName == "byte") return byte.class;
  130. if (typeName == "char") return char.class;
  131. if (typeName == "short") return short.class;
  132. if (typeName == "int") return int.class;
  133. if (typeName == "long") return long.class;
  134. if (typeName == "float") return float.class;
  135. if (typeName == "double") return double.class;
  136. if (typeName == "void") return void.class;
  137. return null;
  138. }
  139. /*pp*/ static Class primitiveTypeFor(Class wrapper) {
  140. if (wrapper == Boolean.class) return Boolean.TYPE;
  141. if (wrapper == Byte.class) return Byte.TYPE;
  142. if (wrapper == Character.class) return Character.TYPE;
  143. if (wrapper == Short.class) return Short.TYPE;
  144. if (wrapper == Integer.class) return Integer.TYPE;
  145. if (wrapper == Long.class) return Long.TYPE;
  146. if (wrapper == Float.class) return Float.TYPE;
  147. if (wrapper == Double.class) return Double.TYPE;
  148. if (wrapper == Void.class) return Void.TYPE;
  149. return null;
  150. }
  151. static Class classForName(String name) throws ClassNotFoundException {
  152. // l.loadClass("int") fails.
  153. Class primitiveType = typeNameToPrimitiveClass(name);
  154. if (primitiveType != null) {
  155. return primitiveType;
  156. }
  157. ClassLoader l = Thread.currentThread().getContextClassLoader();
  158. return l.loadClass(name);
  159. }
  160. /**
  161. * Tests each element on the class arrays for assignability.
  162. *
  163. * @param argClasses arguments to be tested
  164. * @param argTypes arguments from Method
  165. * @return true if each class in argTypes is assignable from the
  166. * corresponding class in argClasses.
  167. */
  168. private static boolean matchArguments(Class[] argClasses, Class[] argTypes) {
  169. boolean match = (argClasses.length == argTypes.length);
  170. for(int j = 0; j < argClasses.length && match; j++) {
  171. Class argType = argTypes[j];
  172. if (argType.isPrimitive()) {
  173. argType = typeToClass(argType);
  174. }
  175. // Consider null an instance of all classes.
  176. if (argClasses[j] != null && !(argType.isAssignableFrom(argClasses[j]))) {
  177. match = false;
  178. }
  179. }
  180. return match;
  181. }
  182. /**
  183. * Tests each element on the class arrays for equality.
  184. *
  185. * @param argClasses arguments to be tested
  186. * @param argTypes arguments from Method
  187. * @return true if each class in argTypes is equal to the
  188. * corresponding class in argClasses.
  189. */
  190. private static boolean matchExplicitArguments(Class[] argClasses, Class[] argTypes) {
  191. boolean match = (argClasses.length == argTypes.length);
  192. for(int j = 0; j < argClasses.length && match; j++) {
  193. Class argType = argTypes[j];
  194. if (argType.isPrimitive()) {
  195. argType = typeToClass(argType);
  196. }
  197. if (argClasses[j] != argType) {
  198. match = false;
  199. }
  200. }
  201. return match;
  202. }
  203. // Pending: throw when the match is ambiguous.
  204. private static Method findPublicMethod(Class declaringClass, String methodName, Class[] argClasses) {
  205. // Many methods are "getters" which take no arguments.
  206. // This permits the following optimisation which
  207. // avoids the expensive call to getMethods().
  208. if (argClasses.length == 0) {
  209. try {
  210. return declaringClass.getMethod(methodName, argClasses);
  211. }
  212. catch (NoSuchMethodException e) {
  213. return null;
  214. }
  215. }
  216. // System.out.println("getMethods " + declaringClass + " for " + methodName);
  217. Method[] methods = declaringClass.getMethods();
  218. ArrayList list = new ArrayList();
  219. for(int i = 0; i < methods.length; i++) {
  220. // Collect all the methods which match the signature.
  221. Method method = methods[i];
  222. if (method.getName().equals(methodName)) {
  223. if (matchArguments(argClasses, method.getParameterTypes())) {
  224. list.add(method);
  225. }
  226. }
  227. }
  228. if (list.size() > 0) {
  229. if (list.size() == 1) {
  230. return (Method)list.get(0);
  231. }
  232. else {
  233. ListIterator iterator = list.listIterator();
  234. Method method;
  235. while (iterator.hasNext()) {
  236. method = (Method)iterator.next();
  237. if (matchExplicitArguments(argClasses, method.getParameterTypes())) {
  238. return method;
  239. }
  240. }
  241. // This list is valid. Should return something.
  242. return (Method)list.get(0);
  243. }
  244. }
  245. return null;
  246. }
  247. // Pending: throw when the match is ambiguous.
  248. private static Method findMethod(Class targetClass, String methodName, Class[] argClasses) {
  249. Method m = findPublicMethod(targetClass, methodName, argClasses);
  250. if (m != null && Modifier.isPublic(m.getDeclaringClass().getModifiers())) {
  251. return m;
  252. }
  253. /*
  254. Search the interfaces for a public version of this method.
  255. Example: the getKeymap() method of a JTextField
  256. returns a package private implementation of the
  257. of the public Keymap interface. In the Keymap
  258. interface there are a number of "properties" one
  259. being the "resolveParent" property implied by the
  260. getResolveParent() method. This getResolveParent()
  261. cannot be called reflectively because the class
  262. itself is not public. Instead we search the class's
  263. interfaces and find the getResolveParent()
  264. method of the Keymap interface - on which invoke
  265. may be applied without error.
  266. So in :-
  267. JTextField o = new JTextField("Hello, world");
  268. Keymap km = o.getKeymap();
  269. Method m1 = km.getClass().getMethod("getResolveParent", new Class[0]);
  270. Method m2 = Keymap.class.getMethod("getResolveParent", new Class[0]);
  271. Methods m1 and m2 are different. The invocation of method
  272. m1 unconditionally throws an IllegalAccessException where
  273. the invocation of m2 will invoke the implementation of the
  274. method. Note that (ignoring the overloading of arguments)
  275. there is only one implementation of the named method which
  276. may be applied to this target.
  277. */
  278. for(Class type = targetClass; type != null; type = type.getSuperclass()) {
  279. Class[] interfaces = type.getInterfaces();
  280. for(int i = 0; i < interfaces.length; i++) {
  281. m = findPublicMethod(interfaces[i], methodName, argClasses);
  282. if (m != null) {
  283. return m;
  284. }
  285. }
  286. }
  287. return null;
  288. }
  289. private static class Signature {
  290. Class targetClass;
  291. String methodName;
  292. Class[] argClasses;
  293. public Signature(Class targetClass, String methodName, Class[] argClasses) {
  294. this.targetClass = targetClass;
  295. this.methodName = methodName;
  296. this.argClasses = argClasses;
  297. }
  298. public boolean equals(Object o2) {
  299. Signature that = (Signature)o2;
  300. if (!(targetClass == that.targetClass)) {
  301. return false;
  302. }
  303. if (!(methodName.equals(that.methodName))) {
  304. return false;
  305. }
  306. if (argClasses.length != that.argClasses.length) {
  307. return false;
  308. }
  309. for (int i = 0; i < argClasses.length; i++) {
  310. if (!(argClasses[i] == that.argClasses[i])) {
  311. return false;
  312. }
  313. }
  314. return true;
  315. }
  316. // Pending(milne) Seek advice an a suitable hash function to use here.
  317. public int hashCode() {
  318. return targetClass.hashCode() * 35 + methodName.hashCode();
  319. }
  320. }
  321. /** A wrapper to findMethod(), which will cache its results if
  322. * isCaching() returns true. See clear().
  323. */
  324. static Method getMethod(Class targetClass, String methodName, Class[] argClasses) {
  325. if (!isCaching()) {
  326. return findMethod(targetClass, methodName, argClasses);
  327. }
  328. Object signature = new Signature(targetClass, methodName, argClasses);
  329. Method m = (Method)methodCache.get(signature);
  330. if (m != null) {
  331. // System.out.println("findMethod found " + methodName + " for " + targetClass);
  332. return m;
  333. }
  334. // System.out.println("findMethod searching " + targetClass + " for " + methodName);
  335. m = findMethod(targetClass, methodName, argClasses);
  336. if (m != null) {
  337. methodCache.put(signature, m);
  338. }
  339. return m;
  340. }
  341. static void setCaching(boolean b) {
  342. methodCache = b ? new HashMap() : null;
  343. }
  344. private static boolean isCaching() {
  345. return methodCache != null;
  346. }
  347. Object invoke() throws Exception {
  348. // System.out.println("Invoking: " + toString());
  349. Object target = getTarget();
  350. String methodName = getMethodName();
  351. Object[] arguments = getArguments();
  352. // Class.forName() won't load classes outside
  353. // of core from a class inside core. Special
  354. // case this method.
  355. if (target == Class.class && methodName == "forName") {
  356. return classForName((String)arguments[0]);
  357. }
  358. Class[] argClasses = new Class[arguments.length];
  359. for(int i = 0; i < arguments.length; i++) {
  360. argClasses[i] = (arguments[i] == null) ? null : arguments[i].getClass();
  361. }
  362. AccessibleObject m = null;
  363. if (target instanceof Class) {
  364. /*
  365. For class methods, simluate the effect of a meta class
  366. by taking the union of the static methods of the
  367. actual class, with the instance methods of "Class.class"
  368. and the overloaded "newInstance" methods defined by the
  369. constructors.
  370. This way "System.class", for example, will perform both
  371. the static method getProperties() and the instance method
  372. getSuperclass() defined in "Class.class".
  373. */
  374. if (methodName == "new") {
  375. methodName = "newInstance";
  376. }
  377. // Provide a short form for array instantiation by faking an nary-constructor.
  378. if (methodName == "newInstance" && ((Class)target).isArray()) {
  379. Object result = Array.newInstance(((Class)target).getComponentType(), arguments.length);
  380. for(int i = 0; i < arguments.length; i++) {
  381. Array.set(result, i, arguments[i]);
  382. }
  383. return result;
  384. }
  385. if (methodName == "newInstance" && arguments.length != 0) {
  386. // The Character class, as of 1.4, does not have a constructor
  387. // which takes a String. All of the other "wrapper" classes
  388. // for Java's primitive types have a String constructor so we
  389. // fake such a constructor here so that this special case can be
  390. // ignored elsewhere.
  391. if (target == Character.class && arguments.length == 1 && argClasses[0] == String.class) {
  392. return new Character(((String)arguments[0]).charAt(0));
  393. }
  394. Constructor[] constructors = ((Class)target).getConstructors();
  395. // PENDING: Implement the resolutuion of ambiguities properly.
  396. for(int i = 0; i < constructors.length; i++) {
  397. Constructor constructor = constructors[i];
  398. if (matchArguments(argClasses, constructor.getParameterTypes())) {
  399. m = constructor;
  400. }
  401. }
  402. }
  403. if (m == null) {
  404. m = getMethod((Class)target, methodName, argClasses);
  405. }
  406. if (m == null) {
  407. m = getMethod(Class.class, methodName, argClasses);
  408. }
  409. }
  410. else {
  411. /*
  412. This special casing of arrays is not necessary, but makes files
  413. involving arrays much shorter and simplifies the archiving infrastrcure.
  414. The Array.set() method introduces an unusual idea - that of a static method
  415. changing the state of an instance. Normally statements with side
  416. effects on objects are instance methods of the objects themselves
  417. and we reinstate this rule (perhaps temporarily) by special-casing arrays.
  418. */
  419. if (target.getClass().isArray() && (methodName == "set" || methodName == "get")) {
  420. int index = ((Integer)arguments[0]).intValue();
  421. if (methodName == "get") {
  422. return Array.get(target, index);
  423. }
  424. else {
  425. Array.set(target, index, arguments[1]);
  426. return null;
  427. }
  428. }
  429. m = getMethod(target.getClass(), methodName, argClasses);
  430. }
  431. if (m != null) {
  432. // System.err.println("Calling \"" + methodName + "\"" + " on " + ((o == null) ? null : target.getClass()));
  433. try {
  434. if (m instanceof Method) {
  435. return ((Method)m).invoke(target, arguments);
  436. }
  437. else {
  438. return ((Constructor)m).newInstance(arguments);
  439. }
  440. }
  441. catch (IllegalAccessException iae) {
  442. throw new IllegalAccessException(toString());
  443. }
  444. catch (InvocationTargetException ite) {
  445. Throwable te = ite.getTargetException();
  446. if (te instanceof Exception) {
  447. throw (Exception)te;
  448. }
  449. else {
  450. throw ite;
  451. }
  452. }
  453. }
  454. throw new NoSuchMethodException(toString());
  455. }
  456. /*pp*/ String instanceName(Object instance) {
  457. return (instance != null && instance.getClass() == String.class)
  458. ? "\""+(String)instance + "\""
  459. : NameGenerator.instanceName(instance);
  460. }
  461. /**
  462. * Prints the value of this statement using a Java-style syntax.
  463. */
  464. public String toString() {
  465. // Respect a subclass's implementation here.
  466. Object target = getTarget();
  467. String methodName = getMethodName();
  468. Object[] arguments = getArguments();
  469. StringBuffer result = new StringBuffer(instanceName(target) + "." + methodName + "(");
  470. int n = arguments.length;
  471. for(int i = 0; i < n; i++) {
  472. result.append(instanceName(arguments[i]));
  473. if (i != n -1) {
  474. result.append(", ");
  475. }
  476. }
  477. result.append(");");
  478. return result.toString();
  479. }
  480. }