1 /* java.lang.reflect.Method - reflection of Java methods
2 Copyright (C) 1998, 2001, 2002, 2005, 2007 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)
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
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
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. */
39 package java.lang.reflect;
41 import gnu.java.lang.ClassHelper;
43 import gnu.java.lang.reflect.MethodSignatureParser;
45 import java.lang.annotation.Annotation;
47 import java.util.Arrays;
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>
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
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
72 * @author Eric Blake <ebb9@email.byu.edu>
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()
80 * @status updated to 1.4
82 public final class Method
83 extends AccessibleObject implements Member, GenericDeclaration
88 private byte[] annotations = null;
89 private byte[] parameterAnnotations = null;
90 private byte[] annotationDefault = null;
91 private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations = null;
93 private static final int METHOD_MODIFIERS
94 = Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE
95 | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC
96 | Modifier.STATIC | Modifier.STRICT | Modifier.SYNCHRONIZED;
98 private static final Annotation[] EMPTY_ANNOTATIONS_ARRAY =
102 * This class is uninstantiable.
104 private Method(Class declaringClass, String name, int slot)
106 this.clazz = declaringClass;
112 * Gets the class that declared this method, or the class where this method
113 * is a non-inherited member.
114 * @return the class that declared this member
116 public Class<?> getDeclaringClass()
122 * Gets the name of this method.
123 * @return the name of this method
125 public String getName()
131 * Return the raw modifiers for this method.
132 * @return the method's modifiers
134 private native int getModifiersInternal();
137 * Gets the modifiers this method uses. Use the <code>Modifier</code>
138 * class to interpret the values. A method can only have a subset of the
139 * following modifiers: public, private, protected, abstract, static,
140 * final, synchronized, native, and strictfp.
142 * @return an integer representing the modifiers to this Member
145 public int getModifiers()
147 return getModifiersInternal() & METHOD_MODIFIERS;
151 * Return true if this method is a bridge method. A bridge method
152 * is generated by the compiler in some situations involving
153 * generics and inheritance.
156 public boolean isBridge()
158 return (getModifiersInternal() & Modifier.BRIDGE) != 0;
162 * Return true if this method is synthetic, false otherwise.
165 public boolean isSynthetic()
167 return (getModifiersInternal() & Modifier.SYNTHETIC) != 0;
171 * Return true if this is a varargs method, that is if
172 * the method takes a variable number of arguments.
175 public boolean isVarArgs()
177 return (getModifiersInternal() & Modifier.VARARGS) != 0;
181 * Gets the return type of this method.
182 * @return the type of this method
184 public native Class<?> getReturnType();
187 * Get the parameter list for this method, in declaration order. If the
188 * method takes no parameters, returns a 0-length array (not null).
190 * @return a list of the types of the method's parameters
192 public native Class<?>[] getParameterTypes();
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
199 * @return a list of the types in the method's throws clause
201 public native Class<?>[] getExceptionTypes();
204 * Compare two objects to see if they are semantically equivalent.
205 * Two Methods are semantically equivalent if they have the same declaring
206 * class, name, parameter list, and return type.
208 * @param o the object to compare to
209 * @return <code>true</code> if they are equal; <code>false</code> if not
211 public boolean equals(Object o)
213 // Implementation note:
214 // The following is a correct but possibly slow implementation.
216 // This class has a private field 'slot' that could be used by
217 // the VM implementation to "link" a particular method to a Class.
218 // In that case equals could be simply implemented as:
220 // if (o instanceof Method)
222 // Method m = (Method)o;
223 // return m.clazz == this.clazz
224 // && m.slot == this.slot;
228 // If a VM uses the Method class as their native/internal representation
229 // then just using the following would be optimal:
233 if (!(o instanceof Method))
235 Method that = (Method)o;
236 if (this.getDeclaringClass() != that.getDeclaringClass())
238 if (!this.getName().equals(that.getName()))
240 if (this.getReturnType() != that.getReturnType())
242 if (!Arrays.equals(this.getParameterTypes(), that.getParameterTypes()))
248 * Get the hash code for the Method. The Method hash code is the hash code
249 * of its name XOR'd with the hash code of its class name.
251 * @return the hash code for the object
253 public int hashCode()
255 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
259 * Get a String representation of the Method. A Method's String
260 * representation is "<modifiers> <returntype>
261 * <methodname>(<paramtypes>) throws <exceptions>", where
262 * everything after ')' is omitted if there are no exceptions.<br> Example:
263 * <code>public static int run(java.lang.Runnable,int)</code>
265 * @return the String representation of the Method
267 public String toString()
269 // 128 is a reasonable buffer initial size for constructor
270 StringBuilder sb = new StringBuilder(128);
271 Modifier.toString(getModifiers(), sb).append(' ');
272 sb.append(ClassHelper.getUserName(getReturnType())).append(' ');
273 sb.append(getDeclaringClass().getName()).append('.');
274 sb.append(getName()).append('(');
275 Class[] c = getParameterTypes();
278 sb.append(ClassHelper.getUserName(c[0]));
279 for (int i = 1; i < c.length; i++)
280 sb.append(',').append(ClassHelper.getUserName(c[i]));
283 c = getExceptionTypes();
286 sb.append(" throws ").append(c[0].getName());
287 for (int i = 1; i < c.length; i++)
288 sb.append(',').append(c[i].getName());
290 return sb.toString();
293 public String toGenericString()
295 // 128 is a reasonable buffer initial size for constructor
296 StringBuilder sb = new StringBuilder(128);
297 Modifier.toString(getModifiers(), sb).append(' ');
298 Constructor.addTypeParameters(sb, getTypeParameters());
299 sb.append(getGenericReturnType()).append(' ');
300 sb.append(getDeclaringClass().getName()).append('.');
301 sb.append(getName()).append('(');
302 Type[] types = getGenericParameterTypes();
303 if (types.length > 0)
306 for (int i = 1; i < types.length; i++)
307 sb.append(',').append(types[i]);
310 types = getGenericExceptionTypes();
311 if (types.length > 0)
313 sb.append(" throws ").append(types[0]);
314 for (int i = 1; i < types.length; i++)
315 sb.append(',').append(types[i]);
317 return sb.toString();
321 * Invoke the method. Arguments are automatically unwrapped and widened,
322 * and the result is automatically wrapped, if needed.<p>
324 * If the method is static, <code>o</code> will be ignored. Otherwise,
325 * the method uses dynamic lookup as described in JLS 15.12.4.4. You cannot
326 * mimic the behavior of nonvirtual lookup (as in super.foo()). This means
327 * you will get a <code>NullPointerException</code> if <code>o</code> is
328 * null, and an <code>IllegalArgumentException</code> if it is incompatible
329 * with the declaring class of the method. If the method takes 0 arguments,
330 * you may use null or a 0-length array for <code>args</code>.<p>
332 * Next, if this Method enforces access control, your runtime context is
333 * evaluated, and you may have an <code>IllegalAccessException</code> if
334 * you could not acces this method in similar compiled code. If the method
335 * is static, and its class is uninitialized, you trigger class
336 * initialization, which may end in a
337 * <code>ExceptionInInitializerError</code>.<p>
339 * Finally, the method is invoked. If it completes normally, the return value
340 * will be null for a void method, a wrapped object for a primitive return
341 * method, or the actual return of an Object method. If it completes
342 * abruptly, the exception is wrapped in an
343 * <code>InvocationTargetException</code>.
345 * @param o the object to invoke the method on
346 * @param args the arguments to the method
347 * @return the return value of the method, wrapped in the appropriate
348 * wrapper if it is primitive
349 * @throws IllegalAccessException if the method could not normally be called
350 * by the Java code (i.e. it is not public)
351 * @throws IllegalArgumentException if the number of arguments is incorrect;
352 * if the arguments types are wrong even with a widening conversion;
353 * or if <code>o</code> is not an instance of the class or interface
354 * declaring this method
355 * @throws InvocationTargetException if the method throws an exception
356 * @throws NullPointerException if <code>o</code> is null and this field
357 * requires an instance
358 * @throws ExceptionInInitializerError if accessing a static method triggered
359 * class initialization, which then failed
361 public Object invoke(Object o, Object... args)
362 throws IllegalAccessException, InvocationTargetException
364 return invokeNative(o, args, clazz, slot);
371 private native Object invokeNative(Object o, Object[] args,
372 Class declaringClass, int slot)
373 throws IllegalAccessException, InvocationTargetException;
376 * Returns an array of <code>TypeVariable</code> objects that represents
377 * the type variables declared by this constructor, in declaration order.
378 * An array of size zero is returned if this class has no type
381 * @return the type variables associated with this class.
382 * @throws GenericSignatureFormatError if the generic signature does
383 * not conform to the format specified in the Virtual Machine
384 * specification, version 3.
387 public TypeVariable<Method>[] getTypeParameters()
389 String sig = getSignature();
391 return new TypeVariable[0];
392 MethodSignatureParser p = new MethodSignatureParser(this, sig);
393 return p.getTypeParameters();
397 * Return the String in the Signature attribute for this method. If there
398 * is no Signature attribute, return null.
400 private native String getSignature();
403 * Returns an array of <code>Type</code> objects that represents
404 * the exception types declared by this method, in declaration order.
405 * An array of size zero is returned if this method declares no
408 * @return the exception types declared by this method.
409 * @throws GenericSignatureFormatError if the generic signature does
410 * not conform to the format specified in the Virtual Machine
411 * specification, version 3.
414 public Type[] getGenericExceptionTypes()
416 String sig = getSignature();
418 return getExceptionTypes();
419 MethodSignatureParser p = new MethodSignatureParser(this, sig);
420 return p.getGenericExceptionTypes();
424 * Returns an array of <code>Type</code> objects that represents
425 * the parameter list for this method, in declaration order.
426 * An array of size zero is returned if this method takes no
429 * @return a list of the types of the method's parameters
430 * @throws GenericSignatureFormatError if the generic signature does
431 * not conform to the format specified in the Virtual Machine
432 * specification, version 3.
435 public Type[] getGenericParameterTypes()
437 String sig = getSignature();
439 return getParameterTypes();
440 MethodSignatureParser p = new MethodSignatureParser(this, sig);
441 return p.getGenericParameterTypes();
445 * Returns the return type of this method.
447 * @return the return type of this method
448 * @throws GenericSignatureFormatError if the generic signature does
449 * not conform to the format specified in the Virtual Machine
450 * specification, version 3.
453 public Type getGenericReturnType()
455 String sig = getSignature();
457 return getReturnType();
458 MethodSignatureParser p = new MethodSignatureParser(this, sig);
459 return p.getGenericReturnType();
463 * If this method is an annotation method, returns the default
464 * value for the method. If there is no default value, or if the
465 * method is not a member of an annotation type, returns null.
466 * Primitive types are wrapped.
468 * @throws TypeNotPresentException if the method returns a Class,
469 * and the class cannot be found
473 public native Object getDefaultValue();
476 * @throws NullPointerException {@inheritDoc}
479 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
480 if (annotationClass == null)
481 throw new NullPointerException();
483 return (T)declaredAnnotations().get(annotationClass);
489 public Annotation[] getDeclaredAnnotations() {
490 return declaredAnnotations().values().toArray(EMPTY_ANNOTATIONS_ARRAY);
493 private synchronized native Map<Class<? extends Annotation>, Annotation> declaredAnnotations();
496 * Returns an array of arrays that represent the annotations on the formal
497 * parameters, in declaration order, of the method represented by
498 * this <tt>Method</tt> object. (Returns an array of length zero if the
499 * underlying method is parameterless. If the method has one or more
500 * parameters, a nested array of length zero is returned for each parameter
501 * with no annotations.) The annotation objects contained in the returned
502 * arrays are serializable. The caller of this method is free to modify
503 * the returned arrays; it will have no effect on the arrays returned to
506 * @return an array of arrays that represent the annotations on the formal
507 * parameters, in declaration order, of the method represented by this
511 public native Annotation[][] getParameterAnnotations();