OSDN Git Service

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