Statement.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /* Statement.java
  2. Copyright (C) 2004, 2005, 2006, Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.beans;
  32. import gnu.java.lang.CPStringBuilder;
  33. import java.lang.reflect.Array;
  34. import java.lang.reflect.Constructor;
  35. import java.lang.reflect.Method;
  36. /**
  37. * <p>A Statement captures the execution of an object method. It stores
  38. * the object, the method to call, and the arguments to the method and
  39. * provides the ability to execute the method on the object, using the
  40. * provided arguments.</p>
  41. *
  42. * @author Jerry Quinn (jlquinn@optonline.net)
  43. * @author Robert Schuster (robertschuster@fsfe.org)
  44. * @since 1.4
  45. */
  46. public class Statement
  47. {
  48. private Object target;
  49. private String methodName;
  50. private Object[] arguments;
  51. /**
  52. * One or the other of these will get a value after execute is
  53. * called once, but not both.
  54. */
  55. private transient Method method;
  56. private transient Constructor ctor;
  57. /**
  58. * <p>Constructs a statement representing the invocation of
  59. * object.methodName(arg[0], arg[1], ...);</p>
  60. *
  61. * <p>If the argument array is null it is replaced with an
  62. * array of zero length.</p>
  63. *
  64. * @param target The object to invoke the method on.
  65. * @param methodName The object method to invoke.
  66. * @param arguments An array of arguments to pass to the method.
  67. */
  68. public Statement(Object target, String methodName, Object[] arguments)
  69. {
  70. this.target = target;
  71. this.methodName = methodName;
  72. this.arguments = (arguments != null) ? arguments : new Object[0];
  73. }
  74. /**
  75. * Execute the statement.
  76. *
  77. * <p>Finds the specified method in the target object and calls it with
  78. * the arguments given in the constructor.</p>
  79. *
  80. * <p>The most specific method according to the JLS(15.11) is used when
  81. * there are multiple methods with the same name.</p>
  82. *
  83. * <p>Execute performs some special handling for methods and
  84. * parameters:
  85. * <ul>
  86. * <li>Static methods can be executed by providing the class as a
  87. * target.</li>
  88. *
  89. * <li>The method name new is reserved to call the constructor
  90. * new() will construct an object and return it. Not useful unless
  91. * an expression :-)</li>
  92. *
  93. * <li>If the target is an array, get and set as defined in
  94. * java.util.List are recognized as valid methods and mapped to the
  95. * methods of the same name in java.lang.reflect.Array.</li>
  96. *
  97. * <li>The native datatype wrappers Boolean, Byte, Character, Double,
  98. * Float, Integer, Long, and Short will map to methods that have
  99. * native datatypes as parameters, in the same way as Method.invoke.
  100. * However, these wrappers also select methods that actually take
  101. * the wrapper type as an argument.</li>
  102. * </ul>
  103. * </p>
  104. *
  105. * <p>The Sun spec doesn't deal with overloading between int and
  106. * Integer carefully. If there are two methods, one that takes an
  107. * Integer and the other taking an int, the method chosen is not
  108. * specified, and can depend on the order in which the methods are
  109. * declared in the source file.</p>
  110. *
  111. * @throws Exception if an exception occurs while locating or
  112. * invoking the method.
  113. */
  114. public void execute() throws Exception
  115. {
  116. doExecute();
  117. }
  118. private static Class wrappers[] =
  119. {
  120. Boolean.class, Byte.class, Character.class, Double.class, Float.class,
  121. Integer.class, Long.class, Short.class
  122. };
  123. private static Class natives[] =
  124. {
  125. Boolean.TYPE, Byte.TYPE, Character.TYPE, Double.TYPE, Float.TYPE,
  126. Integer.TYPE, Long.TYPE, Short.TYPE
  127. };
  128. /** Given a wrapper class, return the native class for it.
  129. * <p>For example, if <code>c</code> is <code>Integer</code>,
  130. * <code>Integer.TYPE</code> is returned.</p>
  131. */
  132. private Class unwrap(Class c)
  133. {
  134. for (int i = 0; i < wrappers.length; i++)
  135. if (c == wrappers[i])
  136. return natives[i];
  137. return null;
  138. }
  139. /** Returns <code>true</code> if all args can be assigned to
  140. * <code>params</code>, <code>false</code> otherwise.
  141. *
  142. * <p>Arrays are guaranteed to be the same length.</p>
  143. */
  144. private boolean compatible(Class[] params, Class[] args)
  145. {
  146. for (int i = 0; i < params.length; i++)
  147. {
  148. // Argument types are derived from argument values. If one of them was
  149. // null then we cannot deduce its type. However null can be assigned to
  150. // any type.
  151. if (args[i] == null)
  152. continue;
  153. // Treat Integer like int if appropriate
  154. Class nativeType = unwrap(args[i]);
  155. if (nativeType != null && params[i].isPrimitive()
  156. && params[i].isAssignableFrom(nativeType))
  157. continue;
  158. if (params[i].isAssignableFrom(args[i]))
  159. continue;
  160. return false;
  161. }
  162. return true;
  163. }
  164. /**
  165. * Returns <code>true</code> if the method arguments in first are
  166. * more specific than the method arguments in second, i.e. all
  167. * arguments in <code>first</code> can be assigned to those in
  168. * <code>second</code>.
  169. *
  170. * <p>A method is more specific if all parameters can also be fed to
  171. * the less specific method, because, e.g. the less specific method
  172. * accepts a base class of the equivalent argument for the more
  173. * specific one.</p>
  174. *
  175. * @param first a <code>Class[]</code> value
  176. * @param second a <code>Class[]</code> value
  177. * @return a <code>boolean</code> value
  178. */
  179. private boolean moreSpecific(Class[] first, Class[] second)
  180. {
  181. for (int j=0; j < first.length; j++)
  182. {
  183. if (second[j].isAssignableFrom(first[j]))
  184. continue;
  185. return false;
  186. }
  187. return true;
  188. }
  189. final Object doExecute() throws Exception
  190. {
  191. Class klazz = (target instanceof Class)
  192. ? (Class) target : target.getClass();
  193. Object args[] = (arguments == null) ? new Object[0] : arguments;
  194. Class argTypes[] = new Class[args.length];
  195. // Retrieve type or use null if the argument is null. The null argument
  196. // type is later used in compatible().
  197. for (int i = 0; i < args.length; i++)
  198. argTypes[i] = (args[i] != null) ? args[i].getClass() : null;
  199. if (target.getClass().isArray())
  200. {
  201. // FIXME: invoke may have to be used. For now, cast to Number
  202. // and hope for the best. If caller didn't behave, we go boom
  203. // and throw the exception.
  204. if (methodName.equals("get") && argTypes.length == 1)
  205. return Array.get(target, ((Number)args[0]).intValue());
  206. if (methodName.equals("set") && argTypes.length == 2)
  207. {
  208. Object obj = Array.get(target, ((Number)args[0]).intValue());
  209. Array.set(target, ((Number)args[0]).intValue(), args[1]);
  210. return obj;
  211. }
  212. throw new NoSuchMethodException("No matching method for statement " + toString());
  213. }
  214. // If we already cached the method, just use it.
  215. if (method != null)
  216. return method.invoke(target, args);
  217. else if (ctor != null)
  218. return ctor.newInstance(args);
  219. // Find a matching method to call. JDK seems to go through all
  220. // this to find the method to call.
  221. // if method name or length don't match, skip
  222. // Need to go through each arg
  223. // If arg is wrapper - check if method arg is matchable builtin
  224. // or same type or super
  225. // - check that method arg is same or super
  226. if (methodName.equals("new") && target instanceof Class)
  227. {
  228. Constructor ctors[] = klazz.getConstructors();
  229. for (int i = 0; i < ctors.length; i++)
  230. {
  231. // Skip methods with wrong number of args.
  232. Class ptypes[] = ctors[i].getParameterTypes();
  233. if (ptypes.length != args.length)
  234. continue;
  235. // Check if method matches
  236. if (!compatible(ptypes, argTypes))
  237. continue;
  238. // Use method[i] if it is more specific.
  239. // FIXME: should this check both directions and throw if
  240. // neither is more specific?
  241. if (ctor == null)
  242. {
  243. ctor = ctors[i];
  244. continue;
  245. }
  246. Class mptypes[] = ctor.getParameterTypes();
  247. if (moreSpecific(ptypes, mptypes))
  248. ctor = ctors[i];
  249. }
  250. if (ctor == null)
  251. throw new InstantiationException("No matching constructor for statement " + toString());
  252. return ctor.newInstance(args);
  253. }
  254. Method methods[] = klazz.getMethods();
  255. for (int i = 0; i < methods.length; i++)
  256. {
  257. // Skip methods with wrong name or number of args.
  258. if (!methods[i].getName().equals(methodName))
  259. continue;
  260. Class ptypes[] = methods[i].getParameterTypes();
  261. if (ptypes.length != args.length)
  262. continue;
  263. // Check if method matches
  264. if (!compatible(ptypes, argTypes))
  265. continue;
  266. // Use method[i] if it is more specific.
  267. // FIXME: should this check both directions and throw if
  268. // neither is more specific?
  269. if (method == null)
  270. {
  271. method = methods[i];
  272. continue;
  273. }
  274. Class mptypes[] = method.getParameterTypes();
  275. if (moreSpecific(ptypes, mptypes))
  276. method = methods[i];
  277. }
  278. if (method == null)
  279. throw new NoSuchMethodException("No matching method for statement " + toString());
  280. // If we were calling Class.forName(String) we intercept and call the
  281. // forName-variant that allows a ClassLoader argument. We take the
  282. // system classloader (aka application classloader) here to make sure
  283. // that application defined classes can be resolved. If we would not
  284. // do that the Class.forName implementation would use the class loader
  285. // of java.beans.Statement which is <null> and cannot resolve application
  286. // defined classes.
  287. if (method.equals(
  288. Class.class.getMethod("forName", new Class[] { String.class })))
  289. return Class.forName(
  290. (String) args[0], true, ClassLoader.getSystemClassLoader());
  291. try {
  292. return method.invoke(target, args);
  293. } catch(IllegalArgumentException iae){
  294. System.err.println("method: " + method);
  295. for(int i=0;i<args.length;i++){
  296. System.err.println("args[" + i + "]: " + args[i]);
  297. }
  298. throw iae;
  299. }
  300. }
  301. /** Return the statement arguments. */
  302. public Object[] getArguments() { return arguments; }
  303. /** Return the statement method name. */
  304. public String getMethodName() { return methodName; }
  305. /** Return the statement object. */
  306. public Object getTarget() { return target; }
  307. /**
  308. * Returns a string representation of this <code>Statement</code>.
  309. *
  310. * @return A string representation of this <code>Statement</code>.
  311. */
  312. public String toString()
  313. {
  314. CPStringBuilder result = new CPStringBuilder();
  315. String targetName;
  316. if (target != null)
  317. targetName = target.getClass().getSimpleName();
  318. else
  319. targetName = "null";
  320. result.append(targetName);
  321. result.append(".");
  322. result.append(methodName);
  323. result.append("(");
  324. String sep = "";
  325. for (int i = 0; i < arguments.length; i++)
  326. {
  327. result.append(sep);
  328. result.append(
  329. ( arguments[i] == null ) ? "null" :
  330. ( arguments[i] instanceof String ) ? "\"" + arguments[i] + "\"" :
  331. arguments[i].getClass().getSimpleName());
  332. sep = ", ";
  333. }
  334. result.append(");");
  335. return result.toString();
  336. }
  337. }