Method.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /* java.lang.reflect.Method - reflection of Java methods
  2. Copyright (C) 1998, 2001, 2002, 2005, 2007, 2008 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.lang.reflect;
  32. import gnu.java.lang.ClassHelper;
  33. import gnu.java.lang.CPStringBuilder;
  34. import gnu.java.lang.reflect.MethodSignatureParser;
  35. import java.lang.annotation.Annotation;
  36. /**
  37. * The Method class represents a member method of a class. It also allows
  38. * dynamic invocation, via reflection. This works for both static and
  39. * instance methods. Invocation on Method objects knows how to do
  40. * widening conversions, but throws {@link IllegalArgumentException} if
  41. * a narrowing conversion would be necessary. You can query for information
  42. * on this Method regardless of location, but invocation access may be limited
  43. * by Java language access controls. If you can't do it in the compiler, you
  44. * can't normally do it here either.<p>
  45. *
  46. * <B>Note:</B> This class returns and accepts types as Classes, even
  47. * primitive types; there are Class types defined that represent each
  48. * different primitive type. They are <code>java.lang.Boolean.TYPE,
  49. * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class,
  50. * byte.class</code>, etc. These are not to be confused with the
  51. * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are
  52. * real classes.<p>
  53. *
  54. * Also note that this is not a serializable class. It is entirely feasible
  55. * to make it serializable using the Externalizable interface, but this is
  56. * on Sun, not me.
  57. *
  58. * @author John Keiser
  59. * @author Eric Blake <ebb9@email.byu.edu>
  60. * @see Member
  61. * @see Class
  62. * @see java.lang.Class#getMethod(String,Class[])
  63. * @see java.lang.Class#getDeclaredMethod(String,Class[])
  64. * @see java.lang.Class#getMethods()
  65. * @see java.lang.Class#getDeclaredMethods()
  66. * @since 1.1
  67. * @status updated to 1.4
  68. */
  69. public final class Method
  70. extends AccessibleObject implements Member, GenericDeclaration
  71. {
  72. private static final int METHOD_MODIFIERS
  73. = Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE
  74. | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC
  75. | Modifier.STATIC | Modifier.STRICT | Modifier.SYNCHRONIZED;
  76. private MethodSignatureParser p;
  77. VMMethod m;
  78. /**
  79. * This class is uninstantiable outside this package.
  80. */
  81. Method(VMMethod m)
  82. {
  83. this.m = m;
  84. m.m = this;
  85. }
  86. /**
  87. * Gets the class that declared this method, or the class where this method
  88. * is a non-inherited member.
  89. * @return the class that declared this member
  90. */
  91. public Class<?> getDeclaringClass()
  92. {
  93. return (Class<?>) m.getDeclaringClass();
  94. }
  95. /**
  96. * Gets the name of this method.
  97. * @return the name of this method
  98. */
  99. public String getName()
  100. {
  101. return m.getName();
  102. }
  103. /**
  104. * Gets the modifiers this method uses. Use the <code>Modifier</code>
  105. * class to interpret the values. A method can only have a subset of the
  106. * following modifiers: public, private, protected, abstract, static,
  107. * final, synchronized, native, and strictfp.
  108. *
  109. * @return an integer representing the modifiers to this Member
  110. * @see Modifier
  111. */
  112. public int getModifiers()
  113. {
  114. return m.getModifiersInternal() & METHOD_MODIFIERS;
  115. }
  116. /**
  117. * Return true if this method is a bridge method. A bridge method
  118. * is generated by the compiler in some situations involving
  119. * generics and inheritance.
  120. * @since 1.5
  121. */
  122. public boolean isBridge()
  123. {
  124. return (m.getModifiersInternal() & Modifier.BRIDGE) != 0;
  125. }
  126. /**
  127. * Return true if this method is synthetic, false otherwise.
  128. * @since 1.5
  129. */
  130. public boolean isSynthetic()
  131. {
  132. return (m.getModifiersInternal() & Modifier.SYNTHETIC) != 0;
  133. }
  134. /**
  135. * Return true if this is a varargs method, that is if
  136. * the method takes a variable number of arguments.
  137. * @since 1.5
  138. */
  139. public boolean isVarArgs()
  140. {
  141. return (m.getModifiersInternal() & Modifier.VARARGS) != 0;
  142. }
  143. /**
  144. * Gets the return type of this method.
  145. * @return the type of this method
  146. */
  147. public Class<?> getReturnType()
  148. {
  149. return (Class<?>) m.getReturnType();
  150. }
  151. /**
  152. * Get the parameter list for this method, in declaration order. If the
  153. * method takes no parameters, returns a 0-length array (not null).
  154. *
  155. * @return a list of the types of the method's parameters
  156. */
  157. public Class<?>[] getParameterTypes()
  158. {
  159. return (Class<?>[]) m.getParameterTypes();
  160. }
  161. /**
  162. * Get the exception types this method says it throws, in no particular
  163. * order. If the method has no throws clause, returns a 0-length array
  164. * (not null).
  165. *
  166. * @return a list of the types in the method's throws clause
  167. */
  168. public Class<?>[] getExceptionTypes()
  169. {
  170. return (Class<?>[]) m.getExceptionTypes();
  171. }
  172. /**
  173. * Compare two objects to see if they are semantically equivalent.
  174. * Two Methods are semantically equivalent if they have the same declaring
  175. * class, name, parameter list, and return type.
  176. *
  177. * @param o the object to compare to
  178. * @return <code>true</code> if they are equal; <code>false</code> if not
  179. */
  180. public boolean equals(Object o)
  181. {
  182. return m.equals(o);
  183. }
  184. /**
  185. * Get the hash code for the Method. The Method hash code is the hash code
  186. * of its name XOR'd with the hash code of its class name.
  187. *
  188. * @return the hash code for the object
  189. */
  190. public int hashCode()
  191. {
  192. return m.getDeclaringClass().getName().hashCode() ^ m.getName().hashCode();
  193. }
  194. /**
  195. * Get a String representation of the Method. A Method's String
  196. * representation is "&lt;modifiers&gt; &lt;returntype&gt;
  197. * &lt;methodname&gt;(&lt;paramtypes&gt;) throws &lt;exceptions&gt;", where
  198. * everything after ')' is omitted if there are no exceptions.<br> Example:
  199. * <code>public static int run(java.lang.Runnable,int)</code>
  200. *
  201. * @return the String representation of the Method
  202. */
  203. public String toString()
  204. {
  205. // 128 is a reasonable buffer initial size for constructor
  206. CPStringBuilder sb = new CPStringBuilder(128);
  207. Modifier.toString(getModifiers(), sb).append(' ');
  208. sb.append(ClassHelper.getUserName(getReturnType())).append(' ');
  209. sb.append(getDeclaringClass().getName()).append('.');
  210. sb.append(getName()).append('(');
  211. Class[] c = getParameterTypes();
  212. if (c.length > 0)
  213. {
  214. sb.append(ClassHelper.getUserName(c[0]));
  215. for (int i = 1; i < c.length; i++)
  216. sb.append(',').append(ClassHelper.getUserName(c[i]));
  217. }
  218. sb.append(')');
  219. c = getExceptionTypes();
  220. if (c.length > 0)
  221. {
  222. sb.append(" throws ").append(c[0].getName());
  223. for (int i = 1; i < c.length; i++)
  224. sb.append(',').append(c[i].getName());
  225. }
  226. return sb.toString();
  227. }
  228. public String toGenericString()
  229. {
  230. // 128 is a reasonable buffer initial size for constructor
  231. CPStringBuilder sb = new CPStringBuilder(128);
  232. Modifier.toString(getModifiers(), sb).append(' ');
  233. Constructor.addTypeParameters(sb, getTypeParameters());
  234. sb.append(getGenericReturnType()).append(' ');
  235. sb.append(getDeclaringClass().getName()).append('.');
  236. sb.append(getName()).append('(');
  237. Type[] types = getGenericParameterTypes();
  238. if (types.length > 0)
  239. {
  240. sb.append(types[0]);
  241. for (int i = 1; i < types.length; i++)
  242. sb.append(',').append(types[i]);
  243. }
  244. sb.append(')');
  245. types = getGenericExceptionTypes();
  246. if (types.length > 0)
  247. {
  248. sb.append(" throws ").append(types[0]);
  249. for (int i = 1; i < types.length; i++)
  250. sb.append(',').append(types[i]);
  251. }
  252. return sb.toString();
  253. }
  254. /**
  255. * Invoke the method. Arguments are automatically unwrapped and widened,
  256. * and the result is automatically wrapped, if needed.<p>
  257. *
  258. * If the method is static, <code>o</code> will be ignored. Otherwise,
  259. * the method uses dynamic lookup as described in JLS 15.12.4.4. You cannot
  260. * mimic the behavior of nonvirtual lookup (as in super.foo()). This means
  261. * you will get a <code>NullPointerException</code> if <code>o</code> is
  262. * null, and an <code>IllegalArgumentException</code> if it is incompatible
  263. * with the declaring class of the method. If the method takes 0 arguments,
  264. * you may use null or a 0-length array for <code>args</code>.<p>
  265. *
  266. * Next, if this Method enforces access control, your runtime context is
  267. * evaluated, and you may have an <code>IllegalAccessException</code> if
  268. * you could not acces this method in similar compiled code. If the method
  269. * is static, and its class is uninitialized, you trigger class
  270. * initialization, which may end in a
  271. * <code>ExceptionInInitializerError</code>.<p>
  272. *
  273. * Finally, the method is invoked. If it completes normally, the return value
  274. * will be null for a void method, a wrapped object for a primitive return
  275. * method, or the actual return of an Object method. If it completes
  276. * abruptly, the exception is wrapped in an
  277. * <code>InvocationTargetException</code>.
  278. *
  279. * @param o the object to invoke the method on
  280. * @param args the arguments to the method
  281. * @return the return value of the method, wrapped in the appropriate
  282. * wrapper if it is primitive
  283. * @throws IllegalAccessException if the method could not normally be called
  284. * by the Java code (i.e. it is not public)
  285. * @throws IllegalArgumentException if the number of arguments is incorrect;
  286. * if the arguments types are wrong even with a widening conversion;
  287. * or if <code>o</code> is not an instance of the class or interface
  288. * declaring this method
  289. * @throws InvocationTargetException if the method throws an exception
  290. * @throws NullPointerException if <code>o</code> is null and this field
  291. * requires an instance
  292. * @throws ExceptionInInitializerError if accessing a static method triggered
  293. * class initialization, which then failed
  294. */
  295. public Object invoke(Object o, Object... args)
  296. throws IllegalAccessException, InvocationTargetException
  297. {
  298. return m.invoke(o, args);
  299. }
  300. /**
  301. * Returns an array of <code>TypeVariable</code> objects that represents
  302. * the type variables declared by this constructor, in declaration order.
  303. * An array of size zero is returned if this class has no type
  304. * variables.
  305. *
  306. * @return the type variables associated with this class.
  307. * @throws GenericSignatureFormatError if the generic signature does
  308. * not conform to the format specified in the Virtual Machine
  309. * specification, version 3.
  310. * @since 1.5
  311. */
  312. public TypeVariable<Method>[] getTypeParameters()
  313. {
  314. if (p == null)
  315. {
  316. String sig = m.getSignature();
  317. if (sig == null)
  318. return (TypeVariable<Method>[]) new TypeVariable[0];
  319. p = new MethodSignatureParser(this, sig);
  320. }
  321. return p.getTypeParameters();
  322. }
  323. /**
  324. * Returns an array of <code>Type</code> objects that represents
  325. * the exception types declared by this method, in declaration order.
  326. * An array of size zero is returned if this method declares no
  327. * exceptions.
  328. *
  329. * @return the exception types declared by this method.
  330. * @throws GenericSignatureFormatError if the generic signature does
  331. * not conform to the format specified in the Virtual Machine
  332. * specification, version 3.
  333. * @since 1.5
  334. */
  335. public Type[] getGenericExceptionTypes()
  336. {
  337. if (p == null)
  338. {
  339. String sig = m.getSignature();
  340. if (sig == null)
  341. return getExceptionTypes();
  342. p = new MethodSignatureParser(this, sig);
  343. }
  344. return p.getGenericExceptionTypes();
  345. }
  346. /**
  347. * Returns an array of <code>Type</code> objects that represents
  348. * the parameter list for this method, in declaration order.
  349. * An array of size zero is returned if this method takes no
  350. * parameters.
  351. *
  352. * @return a list of the types of the method's parameters
  353. * @throws GenericSignatureFormatError if the generic signature does
  354. * not conform to the format specified in the Virtual Machine
  355. * specification, version 3.
  356. * @since 1.5
  357. */
  358. public Type[] getGenericParameterTypes()
  359. {
  360. if (p == null)
  361. {
  362. String sig = m.getSignature();
  363. if (sig == null)
  364. return getParameterTypes();
  365. p = new MethodSignatureParser(this, sig);
  366. }
  367. return p.getGenericParameterTypes();
  368. }
  369. /**
  370. * Returns the return type of this method.
  371. *
  372. * @return the return type of this method
  373. * @throws GenericSignatureFormatError if the generic signature does
  374. * not conform to the format specified in the Virtual Machine
  375. * specification, version 3.
  376. * @since 1.5
  377. */
  378. public Type getGenericReturnType()
  379. {
  380. if (p == null)
  381. {
  382. String sig = m.getSignature();
  383. if (sig == null)
  384. return getReturnType();
  385. p = new MethodSignatureParser(this, sig);
  386. }
  387. return p.getGenericReturnType();
  388. }
  389. /**
  390. * If this method is an annotation method, returns the default
  391. * value for the method. If there is no default value, or if the
  392. * method is not a member of an annotation type, returns null.
  393. * Primitive types are wrapped.
  394. *
  395. * @throws TypeNotPresentException if the method returns a Class,
  396. * and the class cannot be found
  397. *
  398. * @since 1.5
  399. */
  400. public Object getDefaultValue()
  401. {
  402. return m.getDefaultValue();
  403. }
  404. /**
  405. * <p>
  406. * Return an array of arrays representing the annotations on each
  407. * of the method's parameters. The outer array is aligned against
  408. * the parameters of the method and is thus equal in length to
  409. * the number of parameters (thus having a length zero if there are none).
  410. * Each array element in the outer array contains an inner array which
  411. * holds the annotations. This array has a length of zero if the parameter
  412. * has no annotations.
  413. * </p>
  414. * <p>
  415. * The returned annotations are serialized. Changing the annotations has
  416. * no affect on the return value of future calls to this method.
  417. * </p>
  418. *
  419. * @return an array of arrays which represents the annotations used on the
  420. * parameters of this method. The order of the array elements
  421. * matches the declaration order of the parameters.
  422. * @since 1.5
  423. */
  424. public Annotation[][] getParameterAnnotations()
  425. {
  426. return m.getParameterAnnotations();
  427. }
  428. /**
  429. * Returns the element's annotation for the specified annotation type,
  430. * or <code>null</code> if no such annotation exists.
  431. *
  432. * @param annotationClass the type of annotation to look for.
  433. * @return this element's annotation for the specified type, or
  434. * <code>null</code> if no such annotation exists.
  435. * @throws NullPointerException if the annotation class is <code>null</code>.
  436. */
  437. public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
  438. {
  439. // Inescapable as the VM layer is 1.4 based. T will erase to Annotation anyway.
  440. @SuppressWarnings("unchecked")
  441. T ann = (T) m.getAnnotation(annotationClass);
  442. return ann;
  443. }
  444. /**
  445. * Returns all annotations directly defined by the element. If there are
  446. * no annotations directly associated with the element, then a zero-length
  447. * array will be returned. The returned array may be modified by the client
  448. * code, but this will have no effect on the annotation content of this
  449. * class, and hence no effect on the return value of this method for
  450. * future callers.
  451. *
  452. * @return the annotations directly defined by the element.
  453. * @since 1.5
  454. */
  455. public Annotation[] getDeclaredAnnotations()
  456. {
  457. return m.getDeclaredAnnotations();
  458. }
  459. }