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