jamvm

view lib/java/lang/reflect/Method.java @ 395:387051b26a50

Make compatible with changes in GNU Classpath (CVS).
author rlougher
date Wed Jun 04 02:46:32 2008 +0100 (2008-06-04)
parents 768ab36fd30e
children
line source
1 /* java.lang.reflect.Method - reflection of Java methods
2 Copyright (C) 1998, 2001, 2002, 2005 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
38 /*
39 Robert Lougher 17/11/2003.
40 This Classpath reference implementation has been modified to work with JamVM.
41 */
43 package java.lang.reflect;
45 import gnu.java.lang.ClassHelper;
46 import gnu.java.lang.CPStringBuilder;
48 import gnu.java.lang.reflect.MethodSignatureParser;
49 import java.lang.annotation.Annotation;
50 import java.util.Arrays;
52 /**
53 * The Method class represents a member method of a class. It also allows
54 * dynamic invocation, via reflection. This works for both static and
55 * instance methods. Invocation on Method objects knows how to do
56 * widening conversions, but throws {@link IllegalArgumentException} if
57 * a narrowing conversion would be necessary. You can query for information
58 * on this Method regardless of location, but invocation access may be limited
59 * by Java language access controls. If you can't do it in the compiler, you
60 * can't normally do it here either.<p>
61 *
62 * <B>Note:</B> This class returns and accepts types as Classes, even
63 * primitive types; there are Class types defined that represent each
64 * different primitive type. They are <code>java.lang.Boolean.TYPE,
65 * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class,
66 * byte.class</code>, etc. These are not to be confused with the
67 * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are
68 * real classes.<p>
69 *
70 * Also note that this is not a serializable class. It is entirely feasible
71 * to make it serializable using the Externalizable interface, but this is
72 * on Sun, not me.
73 *
74 * @author John Keiser
75 * @author Eric Blake <ebb9@email.byu.edu>
76 * @see Member
77 * @see Class
78 * @see java.lang.Class#getMethod(String,Class[])
79 * @see java.lang.Class#getDeclaredMethod(String,Class[])
80 * @see java.lang.Class#getMethods()
81 * @see java.lang.Class#getDeclaredMethods()
82 * @since 1.1
83 * @status updated to 1.4
84 */
85 public final class Method
86 extends AccessibleObject
87 implements Member, GenericDeclaration
88 {
89 Class declaringClass;
90 private Class[] parameterTypes;
91 private Class[] exceptionTypes;
92 private Class returnType;
93 String name;
94 int slot;
96 /**
97 * This class is uninstantiable.
98 */
99 private Method(Class declaringClass, Class[] parameterTypes, Class[] exceptionTypes, Class returnType, String name, int slot)
100 {
101 this.declaringClass = declaringClass;
102 this.parameterTypes = parameterTypes;
103 this.exceptionTypes = exceptionTypes;
104 this.returnType = returnType;
105 this.name = name;
106 this.slot = slot;
107 }
109 /**
110 * Gets the class that declared this method, or the class where this method
111 * is a non-inherited member.
112 * @return the class that declared this member
113 */
114 public Class getDeclaringClass()
115 {
116 return declaringClass;
117 }
119 /**
120 * Gets the name of this method.
121 * @return the name of this method
122 */
123 public String getName()
124 {
125 return name;
126 }
128 /**
129 * Gets the modifiers this method uses. Use the <code>Modifier</code>
130 * class to interpret the values. A method can only have a subset of the
131 * following modifiers: public, private, protected, abstract, static,
132 * final, synchronized, native, and strictfp.
133 *
134 * @return an integer representing the modifiers to this Member
135 * @see Modifier
136 */
137 public int getModifiers()
138 {
139 return getMethodModifiers(declaringClass, slot);
140 }
142 /**
143 * Return true if this method is a bridge method. A bridge method
144 * is generated by the compiler in some situations involving
145 * generics and inheritance.
146 * @since 1.5
147 */
148 public boolean isBridge()
149 {
150 return (getMethodModifiers(declaringClass, slot) & Modifier.BRIDGE) != 0;
151 }
153 /**
154 * Return true if this method is synthetic, false otherwise.
155 * @since 1.5
156 */
157 public boolean isSynthetic()
158 {
159 return (getMethodModifiers(declaringClass, slot) & Modifier.SYNTHETIC) != 0;
160 }
162 /**
163 * Return true if this is a varargs method, that is if
164 * the method takes a variable number of arguments.
165 * @since 1.5
166 */
167 public boolean isVarArgs()
168 {
169 return (getMethodModifiers(declaringClass, slot) & Modifier.VARARGS) != 0;
170 }
172 /**
173 * Gets the return type of this method.
174 * @return the type of this method
175 */
176 public Class getReturnType()
177 {
178 return returnType;
179 }
181 /**
182 * Get the parameter list for this method, in declaration order. If the
183 * method takes no parameters, returns a 0-length array (not null).
184 *
185 * @return a list of the types of the method's parameters
186 */
187 public Class[] getParameterTypes()
188 {
189 if (parameterTypes == null)
190 return new Class[0];
191 return parameterTypes;
192 }
194 /**
195 * Get the exception types this method says it throws, in no particular
196 * order. If the method has no throws clause, returns a 0-length array
197 * (not null).
198 *
199 * @return a list of the types in the method's throws clause
200 */
201 public Class[] getExceptionTypes()
202 {
203 if (exceptionTypes == null)
204 return new Class[0];
205 return exceptionTypes;
206 }
208 /**
209 * Compare two objects to see if they are semantically equivalent.
210 * Two Methods are semantically equivalent if they have the same declaring
211 * class, name, parameter list, and return type.
212 *
213 * @param o the object to compare to
214 * @return <code>true</code> if they are equal; <code>false</code> if not
215 */
216 public boolean equals(Object o)
217 {
218 // Implementation note:
219 // The following is a correct but possibly slow implementation.
220 //
221 // This class has a private field 'slot' that could be used by
222 // the VM implementation to "link" a particular method to a Class.
223 // In that case equals could be simply implemented as:
224 //
225 // if (o instanceof Method)
226 // {
227 // Method m = (Method)o;
228 // return m.declaringClass == this.declaringClass
229 // && m.slot == this.slot;
230 // }
231 // return false;
232 //
233 // If a VM uses the Method class as their native/internal representation
234 // then just using the following would be optimal:
235 //
236 // return this == o;
237 //
238 if (!(o instanceof Method))
239 return false;
240 Method that = (Method)o;
241 if (this.getDeclaringClass() != that.getDeclaringClass())
242 return false;
243 if (!this.getName().equals(that.getName()))
244 return false;
245 if (this.getReturnType() != that.getReturnType())
246 return false;
247 if (!Arrays.equals(this.getParameterTypes(), that.getParameterTypes()))
248 return false;
249 return true;
250 }
252 /**
253 * Get the hash code for the Method. The Method hash code is the hash code
254 * of its name XOR'd with the hash code of its class name.
255 *
256 * @return the hash code for the object
257 */
258 public int hashCode()
259 {
260 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
261 }
263 /**
264 * Get a String representation of the Method. A Method's String
265 * representation is "&lt;modifiers&gt; &lt;returntype&gt;
266 * &lt;methodname&gt;(&lt;paramtypes&gt;) throws &lt;exceptions&gt;", where
267 * everything after ')' is omitted if there are no exceptions.<br> Example:
268 * <code>public static int run(java.lang.Runnable,int)</code>
269 *
270 * @return the String representation of the Method
271 */
272 public String toString()
273 {
274 // 128 is a reasonable buffer initial size for constructor
275 CPStringBuilder sb = new CPStringBuilder(128);
276 Modifier.toString(getModifiers(), sb).append(' ');
277 sb.append(ClassHelper.getUserName(getReturnType())).append(' ');
278 sb.append(getDeclaringClass().getName()).append('.');
279 sb.append(getName()).append('(');
280 Class[] c = getParameterTypes();
281 if (c.length > 0)
282 {
283 sb.append(ClassHelper.getUserName(c[0]));
284 for (int i = 1; i < c.length; i++)
285 sb.append(',').append(ClassHelper.getUserName(c[i]));
286 }
287 sb.append(')');
288 c = getExceptionTypes();
289 if (c.length > 0)
290 {
291 sb.append(" throws ").append(c[0].getName());
292 for (int i = 1; i < c.length; i++)
293 sb.append(',').append(c[i].getName());
294 }
295 return sb.toString();
296 }
298 public String toGenericString()
299 {
300 // 128 is a reasonable buffer initial size for constructor
301 CPStringBuilder sb = new CPStringBuilder(128);
302 Modifier.toString(getModifiers(), sb).append(' ');
303 Constructor.addTypeParameters(sb, getTypeParameters());
304 sb.append(getGenericReturnType()).append(' ');
305 sb.append(getDeclaringClass().getName()).append('.');
306 sb.append(getName()).append('(');
307 Type[] types = getGenericParameterTypes();
308 if (types.length > 0)
309 {
310 sb.append(types[0]);
311 for (int i = 1; i < types.length; i++)
312 sb.append(',').append(types[i]);
313 }
314 sb.append(')');
315 types = getGenericExceptionTypes();
316 if (types.length > 0)
317 {
318 sb.append(" throws ").append(types[0]);
319 for (int i = 1; i < types.length; i++)
320 sb.append(',').append(types[i]);
321 }
322 return sb.toString();
323 }
325 /**
326 * Invoke the method. Arguments are automatically unwrapped and widened,
327 * and the result is automatically wrapped, if needed.<p>
328 *
329 * If the method is static, <code>o</code> will be ignored. Otherwise,
330 * the method uses dynamic lookup as described in JLS 15.12.4.4. You cannot
331 * mimic the behavior of nonvirtual lookup (as in super.foo()). This means
332 * you will get a <code>NullPointerException</code> if <code>o</code> is
333 * null, and an <code>IllegalArgumentException</code> if it is incompatible
334 * with the declaring class of the method. If the method takes 0 arguments,
335 * you may use null or a 0-length array for <code>args</code>.<p>
336 *
337 * Next, if this Method enforces access control, your runtime context is
338 * evaluated, and you may have an <code>IllegalAccessException</code> if
339 * you could not acces this method in similar compiled code. If the method
340 * is static, and its class is uninitialized, you trigger class
341 * initialization, which may end in a
342 * <code>ExceptionInInitializerError</code>.<p>
343 *
344 * Finally, the method is invoked. If it completes normally, the return value
345 * will be null for a void method, a wrapped object for a primitive return
346 * method, or the actual return of an Object method. If it completes
347 * abruptly, the exception is wrapped in an
348 * <code>InvocationTargetException</code>.
349 *
350 * @param o the object to invoke the method on
351 * @param args the arguments to the method
352 * @return the return value of the method, wrapped in the appropriate
353 * wrapper if it is primitive
354 * @throws IllegalAccessException if the method could not normally be called
355 * by the Java code (i.e. it is not public)
356 * @throws IllegalArgumentException if the number of arguments is incorrect;
357 * if the arguments types are wrong even with a widening conversion;
358 * or if <code>o</code> is not an instance of the class or interface
359 * declaring this method
360 * @throws InvocationTargetException if the method throws an exception
361 * @throws NullPointerException if <code>o</code> is null and this field
362 * requires an instance
363 * @throws ExceptionInInitializerError if accessing a static method triggered
364 * class initialization, which then failed
365 */
366 public Object invoke(Object o, Object[] args)
367 throws IllegalAccessException, InvocationTargetException
368 {
369 return invokeNative(o, args, declaringClass, parameterTypes, returnType, slot, flag);
370 }
372 /**
373 * Returns an array of <code>TypeVariable</code> objects that represents
374 * the type variables declared by this constructor, in declaration order.
375 * An array of size zero is returned if this class has no type
376 * variables.
377 *
378 * @return the type variables associated with this class.
379 * @throws GenericSignatureFormatError if the generic signature does
380 * not conform to the format specified in the Virtual Machine
381 * specification, version 3.
382 * @since 1.5
383 */
384 /* FIXME[GENERICS]: Should be TypeVariable<Method>[] */
385 public TypeVariable[] getTypeParameters()
386 {
387 String sig = getSignature(declaringClass, slot);
388 if (sig == null)
389 return new TypeVariable[0];
390 MethodSignatureParser p = new MethodSignatureParser(this, sig);
391 return p.getTypeParameters();
392 }
394 /**
395 * Returns an array of <code>Type</code> objects that represents
396 * the exception types declared by this method, in declaration order.
397 * An array of size zero is returned if this method declares no
398 * exceptions.
399 *
400 * @return the exception types declared by this method.
401 * @throws GenericSignatureFormatError if the generic signature does
402 * not conform to the format specified in the Virtual Machine
403 * specification, version 3.
404 * @since 1.5
405 */
406 public Type[] getGenericExceptionTypes()
407 {
408 String sig = getSignature(declaringClass, slot);
409 if (sig == null)
410 return getExceptionTypes();
411 MethodSignatureParser p = new MethodSignatureParser(this, sig);
412 return p.getGenericExceptionTypes();
413 }
415 /**
416 * Returns an array of <code>Type</code> objects that represents
417 * the parameter list for this method, in declaration order.
418 * An array of size zero is returned if this method takes no
419 * parameters.
420 *
421 * @return a list of the types of the method's parameters
422 * @throws GenericSignatureFormatError if the generic signature does
423 * not conform to the format specified in the Virtual Machine
424 * specification, version 3.
425 * @since 1.5
426 */
427 public Type[] getGenericParameterTypes()
428 {
429 String sig = getSignature(declaringClass, slot);
430 if (sig == null)
431 return getParameterTypes();
432 MethodSignatureParser p = new MethodSignatureParser(this, sig);
433 return p.getGenericParameterTypes();
434 }
436 /**
437 * Returns the return type of this method.
438 *
439 * @return the return type of this method
440 * @throws GenericSignatureFormatError if the generic signature does
441 * not conform to the format specified in the Virtual Machine
442 * specification, version 3.
443 * @since 1.5
444 */
445 public Type getGenericReturnType()
446 {
447 String sig = getSignature(declaringClass, slot);
448 if (sig == null)
449 return getReturnType();
450 MethodSignatureParser p = new MethodSignatureParser(this, sig);
451 return p.getGenericReturnType();
452 }
454 public Annotation getAnnotation(Class annoClass)
455 {
456 Annotation[] annos = getDeclaredAnnotations();
457 for (int i = 0; i < annos.length; i++)
458 if (annos[i].annotationType() == annoClass)
459 return annos[i];
460 return null;
461 }
463 public Annotation[] getDeclaredAnnotations()
464 {
465 return getDeclaredAnnotationsNative(declaringClass, slot);
466 }
468 public Annotation[][] getParameterAnnotations()
469 {
470 return getParameterAnnotationsNative(declaringClass, slot);
471 }
473 /**
474 * If this method is an annotation method, returns the default
475 * value for the method. If there is no default value, or if the
476 * method is not a member of an annotation type, returns null.
477 * Primitive types are wrapped.
478 *
479 * @throws TypeNotPresentException if the method returns a Class,
480 * and the class cannot be found
481 *
482 * @since 1.5
483 */
484 public Object getDefaultValue()
485 {
486 return getDefaultValueNative(declaringClass, slot);
487 }
489 /*
490 * NATIVE HELPERS
491 */
493 /**
494 * Return the raw modifiers for this method.
495 * @return the method's modifiers
496 */
497 private native int getMethodModifiers(Class declaringClass, int slot);
499 /**
500 * Return the String in the Signature attribute for this method. If there
501 * is no Signature attribute, return null.
502 */
503 private native String getSignature(Class declaringClass, int slot);
505 private native Object invokeNative(Object o, Object[] args, Class declaringClass,
506 Class[] parameterTypes, Class returnType,
507 int slot, boolean noAccessCheck)
508 throws IllegalAccessException, InvocationTargetException;
510 private native Object getDefaultValueNative(Class declaringClass, int slot);
511 private native Annotation[] getDeclaredAnnotationsNative(Class declaringClass, int slot);
512 private native Annotation[][] getParameterAnnotationsNative(Class declaringClass, int slot);
513 }