Method.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. // Method.java - Represent method of class or interface.
  2. /* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2006, 2007 Free Software Foundation
  3. This file is part of libgcj.
  4. This software is copyrighted work licensed under the terms of the
  5. Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
  6. details. */
  7. package java.lang.reflect;
  8. import gnu.gcj.RawData;
  9. import gnu.java.lang.reflect.MethodSignatureParser;
  10. import java.lang.annotation.Annotation;
  11. /**
  12. * The Method class represents a member method of a class. It also allows
  13. * dynamic invocation, via reflection. This works for both static and
  14. * instance methods. Invocation on Method objects knows how to do
  15. * widening conversions, but throws {@link IllegalArgumentException} if
  16. * a narrowing conversion would be necessary. You can query for information
  17. * on this Method regardless of location, but invocation access may be limited
  18. * by Java language access controls. If you can't do it in the compiler, you
  19. * can't normally do it here either.<p>
  20. *
  21. * <B>Note:</B> This class returns and accepts types as Classes, even
  22. * primitive types; there are Class types defined that represent each
  23. * different primitive type. They are <code>java.lang.Boolean.TYPE,
  24. * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class,
  25. * byte.class</code>, etc. These are not to be confused with the
  26. * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are
  27. * real classes.<p>
  28. *
  29. * Also note that this is not a serializable class. It is entirely feasible
  30. * to make it serializable using the Externalizable interface, but this is
  31. * on Sun, not me.
  32. *
  33. * @author John Keiser
  34. * @author Eric Blake <ebb9@email.byu.edu>
  35. * @author Tom Tromey <tromey@redhat.com>
  36. * @see Member
  37. * @see Class
  38. * @see java.lang.Class#getMethod(String,Class[])
  39. * @see java.lang.Class#getDeclaredMethod(String,Class[])
  40. * @see java.lang.Class#getMethods()
  41. * @see java.lang.Class#getDeclaredMethods()
  42. * @since 1.1
  43. * @status updated to 1.4
  44. */
  45. public final class Method
  46. extends AccessibleObject implements Member, GenericDeclaration
  47. {
  48. static final int METHOD_MODIFIERS
  49. = Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE
  50. | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC
  51. | Modifier.STATIC | Modifier.STRICT | Modifier.SYNCHRONIZED;
  52. /**
  53. * This class is uninstantiable.
  54. */
  55. private Method ()
  56. {
  57. }
  58. /**
  59. * Gets the class that declared this method, or the class where this method
  60. * is a non-inherited member.
  61. * @return the class that declared this member
  62. */
  63. public Class<?> getDeclaringClass()
  64. {
  65. return declaringClass;
  66. }
  67. /**
  68. * Gets the name of this method.
  69. * @return the name of this method
  70. */
  71. public native String getName ();
  72. /**
  73. * Return the raw modifiers for this method.
  74. * @return the method's modifiers
  75. */
  76. private native int getModifiersInternal();
  77. /**
  78. * Gets the modifiers this method uses. Use the <code>Modifier</code>
  79. * class to interpret the values. A method can only have a subset of the
  80. * following modifiers: public, private, protected, abstract, static,
  81. * final, synchronized, native, and strictfp.
  82. *
  83. * @return an integer representing the modifiers to this Member
  84. * @see Modifier
  85. */
  86. public int getModifiers()
  87. {
  88. return getModifiersInternal() & METHOD_MODIFIERS;
  89. }
  90. /**
  91. * Return true if this method is a bridge method. A bridge method
  92. * is generated by the compiler in some situations involving
  93. * generics and inheritance.
  94. * @since 1.5
  95. */
  96. public boolean isBridge()
  97. {
  98. return (getModifiersInternal() & Modifier.BRIDGE) != 0;
  99. }
  100. /**
  101. * Return true if this method is synthetic, false otherwise.
  102. * @since 1.5
  103. */
  104. public boolean isSynthetic()
  105. {
  106. return (getModifiersInternal() & Modifier.SYNTHETIC) != 0;
  107. }
  108. /**
  109. * Return true if this is a varargs method, that is if
  110. * the method takes a variable number of arguments.
  111. * @since 1.5
  112. */
  113. public boolean isVarArgs()
  114. {
  115. return (getModifiersInternal() & Modifier.VARARGS) != 0;
  116. }
  117. /**
  118. * Gets the return type of this method.
  119. * @return the type of this method
  120. */
  121. public Class<?> getReturnType ()
  122. {
  123. if (return_type == null)
  124. getType();
  125. return return_type;
  126. }
  127. /**
  128. * Get the parameter list for this method, in declaration order. If the
  129. * method takes no parameters, returns a 0-length array (not null).
  130. *
  131. * @return a list of the types of the method's parameters
  132. */
  133. public Class<?>[] getParameterTypes ()
  134. {
  135. if (parameter_types == null)
  136. getType();
  137. return (Class<?>[]) parameter_types.clone();
  138. }
  139. // Just like getParameterTypes, but don't clone the array.
  140. // Package private for use by VMProxy.
  141. final Class<?>[] internalGetParameterTypes ()
  142. {
  143. if (parameter_types == null)
  144. getType();
  145. return (Class<?>[]) parameter_types;
  146. }
  147. /**
  148. * Get the exception types this method says it throws, in no particular
  149. * order. If the method has no throws clause, returns a 0-length array
  150. * (not null).
  151. *
  152. * @return a list of the types in the method's throws clause
  153. */
  154. public Class<?>[] getExceptionTypes ()
  155. {
  156. if (exception_types == null)
  157. getType();
  158. return (Class<?>[]) exception_types.clone();
  159. }
  160. // Just like getExceptionTypes, but don't clone the array.
  161. // Package private for use by VMProxy.
  162. final Class<?>[] internalGetExceptionTypes ()
  163. {
  164. if (exception_types == null)
  165. getType();
  166. return (Class<?>[]) exception_types;
  167. }
  168. /**
  169. * Compare two objects to see if they are semantically equivalent.
  170. * Two Methods are semantically equivalent if they have the same declaring
  171. * class, name, and parameter list. This ignores different exception
  172. * clauses or return types.
  173. *
  174. * @param o the object to compare to
  175. * @return <code>true</code> if they are equal; <code>false</code> if not
  176. */
  177. public boolean equals (Object obj)
  178. {
  179. if (! (obj instanceof Method))
  180. return false;
  181. Method m = (Method) obj;
  182. return declaringClass == m.declaringClass && offset == m.offset;
  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 getDeclaringClass().getName().hashCode() ^ 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. if (parameter_types == null)
  206. getType ();
  207. StringBuffer b = new StringBuffer ();
  208. int mods = getModifiers();
  209. if (mods != 0)
  210. {
  211. Modifier.toString(mods, b);
  212. b.append(" ");
  213. }
  214. appendClassName (b, return_type);
  215. b.append(" ");
  216. appendClassName (b, declaringClass);
  217. b.append(".");
  218. b.append(getName());
  219. b.append("(");
  220. for (int i = 0; i < parameter_types.length; ++i)
  221. {
  222. appendClassName (b, parameter_types[i]);
  223. if (i < parameter_types.length - 1)
  224. b.append(",");
  225. }
  226. b.append(")");
  227. if (exception_types.length > 0)
  228. {
  229. b.append(" throws ");
  230. for (int i = 0; i < exception_types.length; ++i)
  231. {
  232. appendClassName (b, exception_types[i]);
  233. if (i < exception_types.length - 1)
  234. b.append(",");
  235. }
  236. }
  237. return b.toString();
  238. }
  239. public String toGenericString()
  240. {
  241. // 128 is a reasonable buffer initial size for constructor
  242. StringBuilder sb = new StringBuilder(128);
  243. Modifier.toString(getModifiers(), sb).append(' ');
  244. Constructor.addTypeParameters(sb, getTypeParameters());
  245. sb.append(getGenericReturnType()).append(' ');
  246. sb.append(getDeclaringClass().getName()).append('.');
  247. sb.append(getName()).append('(');
  248. Type[] types = getGenericParameterTypes();
  249. if (types.length > 0)
  250. {
  251. sb.append(types[0]);
  252. for (int i = 1; i < types.length; i++)
  253. sb.append(',').append(types[i]);
  254. }
  255. sb.append(')');
  256. types = getGenericExceptionTypes();
  257. if (types.length > 0)
  258. {
  259. sb.append(" throws ").append(types[0]);
  260. for (int i = 1; i < types.length; i++)
  261. sb.append(',').append(types[i]);
  262. }
  263. return sb.toString();
  264. }
  265. /**
  266. * Invoke the method. Arguments are automatically unwrapped and widened,
  267. * and the result is automatically wrapped, if needed.<p>
  268. *
  269. * If the method is static, <code>o</code> will be ignored. Otherwise,
  270. * the method uses dynamic lookup as described in JLS 15.12.4.4. You cannot
  271. * mimic the behavior of nonvirtual lookup (as in super.foo()). This means
  272. * you will get a <code>NullPointerException</code> if <code>o</code> is
  273. * null, and an <code>IllegalArgumentException</code> if it is incompatible
  274. * with the declaring class of the method. If the method takes 0 arguments,
  275. * you may use null or a 0-length array for <code>args</code>.<p>
  276. *
  277. * Next, if this Method enforces access control, your runtime context is
  278. * evaluated, and you may have an <code>IllegalAccessException</code> if
  279. * you could not acces this method in similar compiled code. If the method
  280. * is static, and its class is uninitialized, you trigger class
  281. * initialization, which may end in a
  282. * <code>ExceptionInInitializerError</code>.<p>
  283. *
  284. * Finally, the method is invoked. If it completes normally, the return value
  285. * will be null for a void method, a wrapped object for a primitive return
  286. * method, or the actual return of an Object method. If it completes
  287. * abruptly, the exception is wrapped in an
  288. * <code>InvocationTargetException</code>.
  289. *
  290. * @param o the object to invoke the method on
  291. * @param args the arguments to the method
  292. * @return the return value of the method, wrapped in the appropriate
  293. * wrapper if it is primitive
  294. * @throws IllegalAccessException if the method could not normally be called
  295. * by the Java code (i.e. it is not public)
  296. * @throws IllegalArgumentException if the number of arguments is incorrect;
  297. * if the arguments types are wrong even with a widening conversion;
  298. * or if <code>o</code> is not an instance of the class or interface
  299. * declaring this method
  300. * @throws InvocationTargetException if the method throws an exception
  301. * @throws NullPointerException if <code>o</code> is null and this field
  302. * requires an instance
  303. * @throws ExceptionInInitializerError if accessing a static method triggered
  304. * class initialization, which then failed
  305. */
  306. public native Object invoke (Object obj, Object... args)
  307. throws IllegalAccessException, IllegalArgumentException,
  308. InvocationTargetException;
  309. /**
  310. * Returns an array of <code>TypeVariable</code> objects that represents
  311. * the type variables declared by this constructor, in declaration order.
  312. * An array of size zero is returned if this class has no type
  313. * variables.
  314. *
  315. * @return the type variables associated with this class.
  316. * @throws GenericSignatureFormatError if the generic signature does
  317. * not conform to the format specified in the Virtual Machine
  318. * specification, version 3.
  319. * @since 1.5
  320. */
  321. public TypeVariable<Method>[] getTypeParameters()
  322. {
  323. String sig = getSignature();
  324. if (sig == null)
  325. return new TypeVariable[0];
  326. MethodSignatureParser p = new MethodSignatureParser(this, sig);
  327. return p.getTypeParameters();
  328. }
  329. /**
  330. * Return the String in the Signature attribute for this method. If there
  331. * is no Signature attribute, return null.
  332. */
  333. private native String getSignature();
  334. /**
  335. * Returns an array of <code>Type</code> objects that represents
  336. * the exception types declared by this method, in declaration order.
  337. * An array of size zero is returned if this method declares no
  338. * exceptions.
  339. *
  340. * @return the exception types declared by this method.
  341. * @throws GenericSignatureFormatError if the generic signature does
  342. * not conform to the format specified in the Virtual Machine
  343. * specification, version 3.
  344. * @since 1.5
  345. */
  346. public Type[] getGenericExceptionTypes()
  347. {
  348. String sig = getSignature();
  349. if (sig == null)
  350. return getExceptionTypes();
  351. MethodSignatureParser p = new MethodSignatureParser(this, sig);
  352. return p.getGenericExceptionTypes();
  353. }
  354. /**
  355. * Returns an array of <code>Type</code> objects that represents
  356. * the parameter list for this method, in declaration order.
  357. * An array of size zero is returned if this method takes no
  358. * parameters.
  359. *
  360. * @return a list of the types of the method's parameters
  361. * @throws GenericSignatureFormatError if the generic signature does
  362. * not conform to the format specified in the Virtual Machine
  363. * specification, version 3.
  364. * @since 1.5
  365. */
  366. public Type[] getGenericParameterTypes()
  367. {
  368. String sig = getSignature();
  369. if (sig == null)
  370. return getParameterTypes();
  371. MethodSignatureParser p = new MethodSignatureParser(this, sig);
  372. return p.getGenericParameterTypes();
  373. }
  374. /**
  375. * Returns the return type of this method.
  376. *
  377. * @return the return type of this method
  378. * @throws GenericSignatureFormatError if the generic signature does
  379. * not conform to the format specified in the Virtual Machine
  380. * specification, version 3.
  381. * @since 1.5
  382. */
  383. public Type getGenericReturnType()
  384. {
  385. String sig = getSignature();
  386. if (sig == null)
  387. return getReturnType();
  388. MethodSignatureParser p = new MethodSignatureParser(this, sig);
  389. return p.getGenericReturnType();
  390. }
  391. /**
  392. * If this method is an annotation method, returns the default
  393. * value for the method. If there is no default value, or if the
  394. * method is not a member of an annotation type, returns null.
  395. * Primitive types are wrapped.
  396. *
  397. * @throws TypeNotPresentException if the method returns a Class,
  398. * and the class cannot be found
  399. *
  400. * @since 1.5
  401. */
  402. public native Object getDefaultValue();
  403. public <T extends Annotation> T getAnnotation(Class<T> annoClass)
  404. {
  405. Annotation[] annos = getDeclaredAnnotations();
  406. for (int i = 0; i < annos.length; ++i)
  407. if (annos[i].annotationType() == annoClass)
  408. return (T) annos[i];
  409. return null;
  410. }
  411. public Annotation[] getDeclaredAnnotations()
  412. {
  413. Annotation[] result = getDeclaredAnnotationsInternal();
  414. if (result == null)
  415. result = new Annotation[0];
  416. return result;
  417. }
  418. public Annotation[][] getParameterAnnotations()
  419. {
  420. // FIXME: should check that we have the right number
  421. // of parameters ...?
  422. Annotation[][] result = getParameterAnnotationsInternal();
  423. if (result == null)
  424. result = new Annotation[0][0];
  425. return result;
  426. }
  427. private native Annotation[] getDeclaredAnnotationsInternal();
  428. private native Annotation[][] getParameterAnnotationsInternal();
  429. private native void getType ();
  430. // Append a class name to a string buffer. We try to print the
  431. // fully-qualified name, the way that a Java programmer would expect
  432. // it to be written. Weirdly, Class has no appropriate method for
  433. // this.
  434. static void appendClassName (StringBuffer buf, Class k)
  435. {
  436. if (k.isArray ())
  437. {
  438. appendClassName (buf, k.getComponentType ());
  439. buf.append ("[]");
  440. }
  441. else
  442. {
  443. // This is correct for primitive and reference types. Really
  444. // we'd like `Main$Inner' to be printed as `Main.Inner', I
  445. // think, but that is a pain.
  446. buf.append (k.getName ());
  447. }
  448. }
  449. // Declaring class.
  450. private Class declaringClass;
  451. // Exception types.
  452. Class[] exception_types;
  453. // Name cache. (Initially null.)
  454. private String name;
  455. // Parameter types.
  456. Class[] parameter_types;
  457. // Return type.
  458. Class return_type;
  459. // Offset in bytes from the start of declaringClass's methods array.
  460. private int offset;
  461. }