2 * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
26 package java.lang.reflect;
28 import java.lang.annotation.Annotation;
31 * A {@code Method} provides information about, and access to, a single method
32 * on a class or interface. The reflected method may be a class method
33 * or an instance method (including an abstract method).
35 * <p>A {@code Method} permits widening conversions to occur when matching the
36 * actual parameters to invoke with the underlying method's formal
37 * parameters, but it throws an {@code IllegalArgumentException} if a
38 * narrowing conversion would occur.
41 * @see java.lang.Class
42 * @see java.lang.Class#getMethods()
43 * @see java.lang.Class#getMethod(String, Class[])
44 * @see java.lang.Class#getDeclaredMethods()
45 * @see java.lang.Class#getDeclaredMethod(String, Class[])
47 * @author Kenneth Russell
48 * @author Nakul Saraiya
51 class Method extends AccessibleObject implements GenericDeclaration,
53 private Class<?> clazz;
55 // This is guaranteed to be interned by the VM in the 1.4
56 // reflection implementation
58 private Class<?> returnType;
59 private Class<?>[] parameterTypes;
60 private Class<?>[] exceptionTypes;
61 private int modifiers;
62 // Generics and annotations support
63 private transient String signature;
64 private byte[] annotations;
65 private byte[] parameterAnnotations;
66 private byte[] annotationDefault;
67 // For sharing of MethodAccessors. This branching structure is
68 // currently only two levels deep (i.e., one root Method and
69 // potentially many Method objects pointing to it.)
72 // Generics infrastructure
74 private String getGenericSignature() {return signature;}
77 * Package-private constructor used by ReflectAccess to enable
78 * instantiation of these objects in Java code from the java.lang
79 * package via sun.reflect.LangReflectAccess.
81 Method(Class<?> declaringClass,
83 Class<?>[] parameterTypes,
85 Class<?>[] checkedExceptions,
90 byte[] parameterAnnotations,
91 byte[] annotationDefault)
93 this.clazz = declaringClass;
95 this.parameterTypes = parameterTypes;
96 this.returnType = returnType;
97 this.exceptionTypes = checkedExceptions;
98 this.modifiers = modifiers;
100 this.signature = signature;
101 this.annotations = annotations;
102 this.parameterAnnotations = parameterAnnotations;
103 this.annotationDefault = annotationDefault;
107 * Package-private routine (exposed to java.lang.Class via
108 * ReflectAccess) which returns a copy of this Method. The copy's
109 * "root" field points to this Method.
112 // This routine enables sharing of MethodAccessor objects
113 // among Method objects which refer to the same underlying
114 // method in the VM. (All of this contortion is only necessary
115 // because of the "accessibility" bit in AccessibleObject,
116 // which implicitly requires that new java.lang.reflect
117 // objects be fabricated for each reflective call on Class
119 Method res = new Method(clazz, name, parameterTypes, returnType,
120 exceptionTypes, modifiers, slot, signature,
121 annotations, parameterAnnotations, annotationDefault);
127 * Returns the {@code Class} object representing the class or interface
128 * that declares the method represented by this {@code Method} object.
130 public Class<?> getDeclaringClass() {
135 * Returns the name of the method represented by this {@code Method}
136 * object, as a {@code String}.
138 public String getName() {
143 * Returns the Java language modifiers for the method represented
144 * by this {@code Method} object, as an integer. The {@code Modifier} class should
145 * be used to decode the modifiers.
149 public int getModifiers() {
154 * Returns an array of {@code TypeVariable} objects that represent the
155 * type variables declared by the generic declaration represented by this
156 * {@code GenericDeclaration} object, in declaration order. Returns an
157 * array of length 0 if the underlying generic declaration declares no type
160 * @return an array of {@code TypeVariable} objects that represent
161 * the type variables declared by this generic declaration
162 * @throws GenericSignatureFormatError if the generic
163 * signature of this generic declaration does not conform to
164 * the format specified in
165 * <cite>The Java™ Virtual Machine Specification</cite>
168 public TypeVariable<Method>[] getTypeParameters() {
169 throw new UnsupportedOperationException();
173 * Returns a {@code Class} object that represents the formal return type
174 * of the method represented by this {@code Method} object.
176 * @return the return type for the method this object represents
178 public Class<?> getReturnType() {
183 * Returns a {@code Type} object that represents the formal return
184 * type of the method represented by this {@code Method} object.
186 * <p>If the return type is a parameterized type,
187 * the {@code Type} object returned must accurately reflect
188 * the actual type parameters used in the source code.
190 * <p>If the return type is a type variable or a parameterized type, it
191 * is created. Otherwise, it is resolved.
193 * @return a {@code Type} object that represents the formal return
194 * type of the underlying method
195 * @throws GenericSignatureFormatError
196 * if the generic method signature does not conform to the format
198 * <cite>The Java™ Virtual Machine Specification</cite>
199 * @throws TypeNotPresentException if the underlying method's
200 * return type refers to a non-existent type declaration
201 * @throws MalformedParameterizedTypeException if the
202 * underlying method's return typed refers to a parameterized
203 * type that cannot be instantiated for any reason
206 public Type getGenericReturnType() {
207 throw new UnsupportedOperationException();
212 * Returns an array of {@code Class} objects that represent the formal
213 * parameter types, in declaration order, of the method
214 * represented by this {@code Method} object. Returns an array of length
215 * 0 if the underlying method takes no parameters.
217 * @return the parameter types for the method this object
220 public Class<?>[] getParameterTypes() {
221 return (Class<?>[]) parameterTypes.clone();
225 * Returns an array of {@code Type} objects that represent the formal
226 * parameter types, in declaration order, of the method represented by
227 * this {@code Method} object. Returns an array of length 0 if the
228 * underlying method takes no parameters.
230 * <p>If a formal parameter type is a parameterized type,
231 * the {@code Type} object returned for it must accurately reflect
232 * the actual type parameters used in the source code.
234 * <p>If a formal parameter type is a type variable or a parameterized
235 * type, it is created. Otherwise, it is resolved.
237 * @return an array of Types that represent the formal
238 * parameter types of the underlying method, in declaration order
239 * @throws GenericSignatureFormatError
240 * if the generic method signature does not conform to the format
242 * <cite>The Java™ Virtual Machine Specification</cite>
243 * @throws TypeNotPresentException if any of the parameter
244 * types of the underlying method refers to a non-existent type
246 * @throws MalformedParameterizedTypeException if any of
247 * the underlying method's parameter types refer to a parameterized
248 * type that cannot be instantiated for any reason
251 public Type[] getGenericParameterTypes() {
252 throw new UnsupportedOperationException();
257 * Returns an array of {@code Class} objects that represent
258 * the types of the exceptions declared to be thrown
259 * by the underlying method
260 * represented by this {@code Method} object. Returns an array of length
261 * 0 if the method declares no exceptions in its {@code throws} clause.
263 * @return the exception types declared as being thrown by the
264 * method this object represents
266 public Class<?>[] getExceptionTypes() {
267 return (Class<?>[]) exceptionTypes.clone();
271 * Returns an array of {@code Type} objects that represent the
272 * exceptions declared to be thrown by this {@code Method} object.
273 * Returns an array of length 0 if the underlying method declares
274 * no exceptions in its {@code throws} clause.
276 * <p>If an exception type is a type variable or a parameterized
277 * type, it is created. Otherwise, it is resolved.
279 * @return an array of Types that represent the exception types
280 * thrown by the underlying method
281 * @throws GenericSignatureFormatError
282 * if the generic method signature does not conform to the format
284 * <cite>The Java™ Virtual Machine Specification</cite>
285 * @throws TypeNotPresentException if the underlying method's
286 * {@code throws} clause refers to a non-existent type declaration
287 * @throws MalformedParameterizedTypeException if
288 * the underlying method's {@code throws} clause refers to a
289 * parameterized type that cannot be instantiated for any reason
292 public Type[] getGenericExceptionTypes() {
293 throw new UnsupportedOperationException();
297 * Compares this {@code Method} against the specified object. Returns
298 * true if the objects are the same. Two {@code Methods} are the same if
299 * they were declared by the same class and have the same name
300 * and formal parameter types and return type.
302 public boolean equals(Object obj) {
303 if (obj != null && obj instanceof Method) {
304 Method other = (Method)obj;
305 if ((getDeclaringClass() == other.getDeclaringClass())
306 && (getName() == other.getName())) {
307 if (!returnType.equals(other.getReturnType()))
309 /* Avoid unnecessary cloning */
310 Class<?>[] params1 = parameterTypes;
311 Class<?>[] params2 = other.parameterTypes;
312 if (params1.length == params2.length) {
313 for (int i = 0; i < params1.length; i++) {
314 if (params1[i] != params2[i])
325 * Returns a hashcode for this {@code Method}. The hashcode is computed
326 * as the exclusive-or of the hashcodes for the underlying
327 * method's declaring class name and the method's name.
329 public int hashCode() {
330 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
334 * Returns a string describing this {@code Method}. The string is
335 * formatted as the method access modifiers, if any, followed by
336 * the method return type, followed by a space, followed by the
337 * class declaring the method, followed by a period, followed by
338 * the method name, followed by a parenthesized, comma-separated
339 * list of the method's formal parameter types. If the method
340 * throws checked exceptions, the parameter list is followed by a
341 * space, followed by the word throws followed by a
342 * comma-separated list of the thrown exception types.
345 * public boolean java.lang.Object.equals(java.lang.Object)
348 * <p>The access modifiers are placed in canonical order as
349 * specified by "The Java Language Specification". This is
350 * {@code public}, {@code protected} or {@code private} first,
351 * and then other modifiers in the following order:
352 * {@code abstract}, {@code static}, {@code final},
353 * {@code synchronized}, {@code native}, {@code strictfp}.
355 public String toString() {
357 StringBuilder sb = new StringBuilder();
358 int mod = getModifiers() & Modifier.methodModifiers();
360 sb.append(Modifier.toString(mod)).append(' ');
362 sb.append(Field.getTypeName(getReturnType())).append(' ');
363 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
364 sb.append(getName()).append('(');
365 Class<?>[] params = parameterTypes; // avoid clone
366 for (int j = 0; j < params.length; j++) {
367 sb.append(Field.getTypeName(params[j]));
368 if (j < (params.length - 1))
372 Class<?>[] exceptions = exceptionTypes; // avoid clone
373 if (exceptions.length > 0) {
374 sb.append(" throws ");
375 for (int k = 0; k < exceptions.length; k++) {
376 sb.append(exceptions[k].getName());
377 if (k < (exceptions.length - 1))
381 return sb.toString();
382 } catch (Exception e) {
383 return "<" + e + ">";
388 * Returns a string describing this {@code Method}, including
389 * type parameters. The string is formatted as the method access
390 * modifiers, if any, followed by an angle-bracketed
391 * comma-separated list of the method's type parameters, if any,
392 * followed by the method's generic return type, followed by a
393 * space, followed by the class declaring the method, followed by
394 * a period, followed by the method name, followed by a
395 * parenthesized, comma-separated list of the method's generic
396 * formal parameter types.
398 * If this method was declared to take a variable number of
399 * arguments, instead of denoting the last parameter as
400 * "<tt><i>Type</i>[]</tt>", it is denoted as
401 * "<tt><i>Type</i>...</tt>".
403 * A space is used to separate access modifiers from one another
404 * and from the type parameters or return type. If there are no
405 * type parameters, the type parameter list is elided; if the type
406 * parameter list is present, a space separates the list from the
407 * class name. If the method is declared to throw exceptions, the
408 * parameter list is followed by a space, followed by the word
409 * throws followed by a comma-separated list of the generic thrown
410 * exception types. If there are no type parameters, the type
411 * parameter list is elided.
413 * <p>The access modifiers are placed in canonical order as
414 * specified by "The Java Language Specification". This is
415 * {@code public}, {@code protected} or {@code private} first,
416 * and then other modifiers in the following order:
417 * {@code abstract}, {@code static}, {@code final},
418 * {@code synchronized}, {@code native}, {@code strictfp}.
420 * @return a string describing this {@code Method},
421 * include type parameters
425 public String toGenericString() {
427 StringBuilder sb = new StringBuilder();
428 int mod = getModifiers() & Modifier.methodModifiers();
430 sb.append(Modifier.toString(mod)).append(' ');
432 TypeVariable<?>[] typeparms = getTypeParameters();
433 if (typeparms.length > 0) {
434 boolean first = true;
436 for(TypeVariable<?> typeparm: typeparms) {
439 // Class objects can't occur here; no need to test
440 // and call Class.getName().
441 sb.append(typeparm.toString());
447 Type genRetType = getGenericReturnType();
448 sb.append( ((genRetType instanceof Class<?>)?
449 Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
452 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
453 sb.append(getName()).append('(');
454 Type[] params = getGenericParameterTypes();
455 for (int j = 0; j < params.length; j++) {
456 String param = (params[j] instanceof Class)?
457 Field.getTypeName((Class)params[j]):
458 (params[j].toString());
459 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
460 param = param.replaceFirst("\\[\\]$", "...");
462 if (j < (params.length - 1))
466 Type[] exceptions = getGenericExceptionTypes();
467 if (exceptions.length > 0) {
468 sb.append(" throws ");
469 for (int k = 0; k < exceptions.length; k++) {
470 sb.append((exceptions[k] instanceof Class)?
471 ((Class)exceptions[k]).getName():
472 exceptions[k].toString());
473 if (k < (exceptions.length - 1))
477 return sb.toString();
478 } catch (Exception e) {
479 return "<" + e + ">";
484 * Invokes the underlying method represented by this {@code Method}
485 * object, on the specified object with the specified parameters.
486 * Individual parameters are automatically unwrapped to match
487 * primitive formal parameters, and both primitive and reference
488 * parameters are subject to method invocation conversions as
491 * <p>If the underlying method is static, then the specified {@code obj}
492 * argument is ignored. It may be null.
494 * <p>If the number of formal parameters required by the underlying method is
495 * 0, the supplied {@code args} array may be of length 0 or null.
497 * <p>If the underlying method is an instance method, it is invoked
498 * using dynamic method lookup as documented in The Java Language
499 * Specification, Second Edition, section 15.12.4.4; in particular,
500 * overriding based on the runtime type of the target object will occur.
502 * <p>If the underlying method is static, the class that declared
503 * the method is initialized if it has not already been initialized.
505 * <p>If the method completes normally, the value it returns is
506 * returned to the caller of invoke; if the value has a primitive
507 * type, it is first appropriately wrapped in an object. However,
508 * if the value has the type of an array of a primitive type, the
509 * elements of the array are <i>not</i> wrapped in objects; in
510 * other words, an array of primitive type is returned. If the
511 * underlying method return type is void, the invocation returns
514 * @param obj the object the underlying method is invoked from
515 * @param args the arguments used for the method call
516 * @return the result of dispatching the method represented by
517 * this object on {@code obj} with parameters
520 * @exception IllegalAccessException if this {@code Method} object
521 * is enforcing Java language access control and the underlying
522 * method is inaccessible.
523 * @exception IllegalArgumentException if the method is an
524 * instance method and the specified object argument
525 * is not an instance of the class or interface
526 * declaring the underlying method (or of a subclass
527 * or implementor thereof); if the number of actual
528 * and formal parameters differ; if an unwrapping
529 * conversion for primitive arguments fails; or if,
530 * after possible unwrapping, a parameter value
531 * cannot be converted to the corresponding formal
532 * parameter type by a method invocation conversion.
533 * @exception InvocationTargetException if the underlying method
534 * throws an exception.
535 * @exception NullPointerException if the specified object is null
536 * and the method is an instance method.
537 * @exception ExceptionInInitializerError if the initialization
538 * provoked by this method fails.
540 public Object invoke(Object obj, Object... args)
541 throws IllegalAccessException, IllegalArgumentException,
542 InvocationTargetException
544 throw new UnsupportedOperationException();
548 * Returns {@code true} if this method is a bridge
549 * method; returns {@code false} otherwise.
551 * @return true if and only if this method is a bridge
552 * method as defined by the Java Language Specification.
555 public boolean isBridge() {
556 return (getModifiers() & Modifier.BRIDGE) != 0;
560 * Returns {@code true} if this method was declared to take
561 * a variable number of arguments; returns {@code false}
564 * @return {@code true} if an only if this method was declared to
565 * take a variable number of arguments.
568 public boolean isVarArgs() {
569 return (getModifiers() & Modifier.VARARGS) != 0;
573 * Returns {@code true} if this method is a synthetic
574 * method; returns {@code false} otherwise.
576 * @return true if and only if this method is a synthetic
577 * method as defined by the Java Language Specification.
580 public boolean isSynthetic() {
581 return Modifier.isSynthetic(getModifiers());
585 * @throws NullPointerException {@inheritDoc}
588 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
589 if (annotationClass == null)
590 throw new NullPointerException();
592 throw new UnsupportedOperationException();
598 public Annotation[] getDeclaredAnnotations() {
599 throw new UnsupportedOperationException();
603 * Returns the default value for the annotation member represented by
604 * this {@code Method} instance. If the member is of a primitive type,
605 * an instance of the corresponding wrapper type is returned. Returns
606 * null if no default is associated with the member, or if the method
607 * instance does not represent a declared member of an annotation type.
609 * @return the default value for the annotation member represented
610 * by this {@code Method} instance.
611 * @throws TypeNotPresentException if the annotation is of type
612 * {@link Class} and no definition can be found for the
613 * default class value.
616 public Object getDefaultValue() {
617 if (annotationDefault == null)
619 throw new UnsupportedOperationException();
623 * Returns an array of arrays that represent the annotations on the formal
624 * parameters, in declaration order, of the method represented by
625 * this {@code Method} object. (Returns an array of length zero if the
626 * underlying method is parameterless. If the method has one or more
627 * parameters, a nested array of length zero is returned for each parameter
628 * with no annotations.) The annotation objects contained in the returned
629 * arrays are serializable. The caller of this method is free to modify
630 * the returned arrays; it will have no effect on the arrays returned to
633 * @return an array of arrays that represent the annotations on the formal
634 * parameters, in declaration order, of the method represented by this
638 public Annotation[][] getParameterAnnotations() {
639 int numParameters = parameterTypes.length;
640 if (parameterAnnotations == null)
641 return new Annotation[numParameters][0];
643 throw new UnsupportedOperationException();