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;
29 import org.apidesign.bck2brwsr.core.JavaScriptBody;
32 * A {@code Method} provides information about, and access to, a single method
33 * on a class or interface. The reflected method may be a class method
34 * or an instance method (including an abstract method).
36 * <p>A {@code Method} permits widening conversions to occur when matching the
37 * actual parameters to invoke with the underlying method's formal
38 * parameters, but it throws an {@code IllegalArgumentException} if a
39 * narrowing conversion would occur.
42 * @see java.lang.Class
43 * @see java.lang.Class#getMethods()
44 * @see java.lang.Class#getMethod(String, Class[])
45 * @see java.lang.Class#getDeclaredMethods()
46 * @see java.lang.Class#getDeclaredMethod(String, Class[])
48 * @author Kenneth Russell
49 * @author Nakul Saraiya
52 class Method extends AccessibleObject implements GenericDeclaration,
54 private final Class<?> clazz;
55 private final String name;
56 private final Object data;
57 private int modifiers;
59 // Generics infrastructure
61 private String getGenericSignature() {return null;}
64 * Package-private constructor used by ReflectAccess to enable
65 * instantiation of these objects in Java code from the java.lang
66 * package via sun.reflect.LangReflectAccess.
68 Method(Class<?> declaringClass,
69 String name, Object data)
71 this.clazz = declaringClass;
77 * Package-private routine (exposed to java.lang.Class via
78 * ReflectAccess) which returns a copy of this Method. The copy's
79 * "root" field points to this Method.
86 * Returns the {@code Class} object representing the class or interface
87 * that declares the method represented by this {@code Method} object.
89 public Class<?> getDeclaringClass() {
94 * Returns the name of the method represented by this {@code Method}
95 * object, as a {@code String}.
97 public String getName() {
102 * Returns the Java language modifiers for the method represented
103 * by this {@code Method} object, as an integer. The {@code Modifier} class should
104 * be used to decode the modifiers.
108 public int getModifiers() {
113 * Returns an array of {@code TypeVariable} objects that represent the
114 * type variables declared by the generic declaration represented by this
115 * {@code GenericDeclaration} object, in declaration order. Returns an
116 * array of length 0 if the underlying generic declaration declares no type
119 * @return an array of {@code TypeVariable} objects that represent
120 * the type variables declared by this generic declaration
121 * @throws GenericSignatureFormatError if the generic
122 * signature of this generic declaration does not conform to
123 * the format specified in
124 * <cite>The Java™ Virtual Machine Specification</cite>
127 public TypeVariable<Method>[] getTypeParameters() {
128 throw new UnsupportedOperationException();
132 * Returns a {@code Class} object that represents the formal return type
133 * of the method represented by this {@code Method} object.
135 * @return the return type for the method this object represents
137 public Class<?> getReturnType() {
138 throw new UnsupportedOperationException();
142 * Returns a {@code Type} object that represents the formal return
143 * type of the method represented by this {@code Method} object.
145 * <p>If the return type is a parameterized type,
146 * the {@code Type} object returned must accurately reflect
147 * the actual type parameters used in the source code.
149 * <p>If the return type is a type variable or a parameterized type, it
150 * is created. Otherwise, it is resolved.
152 * @return a {@code Type} object that represents the formal return
153 * type of the underlying method
154 * @throws GenericSignatureFormatError
155 * if the generic method signature does not conform to the format
157 * <cite>The Java™ Virtual Machine Specification</cite>
158 * @throws TypeNotPresentException if the underlying method's
159 * return type refers to a non-existent type declaration
160 * @throws MalformedParameterizedTypeException if the
161 * underlying method's return typed refers to a parameterized
162 * type that cannot be instantiated for any reason
165 public Type getGenericReturnType() {
166 throw new UnsupportedOperationException();
171 * Returns an array of {@code Class} objects that represent the formal
172 * parameter types, in declaration order, of the method
173 * represented by this {@code Method} object. Returns an array of length
174 * 0 if the underlying method takes no parameters.
176 * @return the parameter types for the method this object
179 public Class<?>[] getParameterTypes() {
180 throw new UnsupportedOperationException();
181 //return (Class<?>[]) parameterTypes.clone();
185 * Returns an array of {@code Type} objects that represent the formal
186 * parameter types, in declaration order, of the method represented by
187 * this {@code Method} object. Returns an array of length 0 if the
188 * underlying method takes no parameters.
190 * <p>If a formal parameter type is a parameterized type,
191 * the {@code Type} object returned for it must accurately reflect
192 * the actual type parameters used in the source code.
194 * <p>If a formal parameter type is a type variable or a parameterized
195 * type, it is created. Otherwise, it is resolved.
197 * @return an array of Types that represent the formal
198 * parameter types of the underlying method, in declaration order
199 * @throws GenericSignatureFormatError
200 * if the generic method signature does not conform to the format
202 * <cite>The Java™ Virtual Machine Specification</cite>
203 * @throws TypeNotPresentException if any of the parameter
204 * types of the underlying method refers to a non-existent type
206 * @throws MalformedParameterizedTypeException if any of
207 * the underlying method's parameter types refer to a parameterized
208 * type that cannot be instantiated for any reason
211 public Type[] getGenericParameterTypes() {
212 throw new UnsupportedOperationException();
217 * Returns an array of {@code Class} objects that represent
218 * the types of the exceptions declared to be thrown
219 * by the underlying method
220 * represented by this {@code Method} object. Returns an array of length
221 * 0 if the method declares no exceptions in its {@code throws} clause.
223 * @return the exception types declared as being thrown by the
224 * method this object represents
226 public Class<?>[] getExceptionTypes() {
227 throw new UnsupportedOperationException();
228 //return (Class<?>[]) exceptionTypes.clone();
232 * Returns an array of {@code Type} objects that represent the
233 * exceptions declared to be thrown by this {@code Method} object.
234 * Returns an array of length 0 if the underlying method declares
235 * no exceptions in its {@code throws} clause.
237 * <p>If an exception type is a type variable or a parameterized
238 * type, it is created. Otherwise, it is resolved.
240 * @return an array of Types that represent the exception types
241 * thrown by the underlying method
242 * @throws GenericSignatureFormatError
243 * if the generic method signature does not conform to the format
245 * <cite>The Java™ Virtual Machine Specification</cite>
246 * @throws TypeNotPresentException if the underlying method's
247 * {@code throws} clause refers to a non-existent type declaration
248 * @throws MalformedParameterizedTypeException if
249 * the underlying method's {@code throws} clause refers to a
250 * parameterized type that cannot be instantiated for any reason
253 public Type[] getGenericExceptionTypes() {
254 throw new UnsupportedOperationException();
258 * Compares this {@code Method} against the specified object. Returns
259 * true if the objects are the same. Two {@code Methods} are the same if
260 * they were declared by the same class and have the same name
261 * and formal parameter types and return type.
263 public boolean equals(Object obj) {
264 if (obj != null && obj instanceof Method) {
265 Method other = (Method)obj;
266 return data == other.data;
272 * Returns a hashcode for this {@code Method}. The hashcode is computed
273 * as the exclusive-or of the hashcodes for the underlying
274 * method's declaring class name and the method's name.
276 public int hashCode() {
277 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
281 * Returns a string describing this {@code Method}. The string is
282 * formatted as the method access modifiers, if any, followed by
283 * the method return type, followed by a space, followed by the
284 * class declaring the method, followed by a period, followed by
285 * the method name, followed by a parenthesized, comma-separated
286 * list of the method's formal parameter types. If the method
287 * throws checked exceptions, the parameter list is followed by a
288 * space, followed by the word throws followed by a
289 * comma-separated list of the thrown exception types.
292 * public boolean java.lang.Object.equals(java.lang.Object)
295 * <p>The access modifiers are placed in canonical order as
296 * specified by "The Java Language Specification". This is
297 * {@code public}, {@code protected} or {@code private} first,
298 * and then other modifiers in the following order:
299 * {@code abstract}, {@code static}, {@code final},
300 * {@code synchronized}, {@code native}, {@code strictfp}.
302 public String toString() {
304 StringBuilder sb = new StringBuilder();
305 int mod = getModifiers() & Modifier.methodModifiers();
307 sb.append(Modifier.toString(mod)).append(' ');
309 sb.append(Field.getTypeName(getReturnType())).append(' ');
310 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
311 sb.append(getName()).append('(');
313 Class<?>[] params = parameterTypes; // avoid clone
314 for (int j = 0; j < params.length; j++) {
315 sb.append(Field.getTypeName(params[j]));
316 if (j < (params.length - 1))
320 Class<?>[] exceptions = exceptionTypes; // avoid clone
321 if (exceptions.length > 0) {
322 sb.append(" throws ");
323 for (int k = 0; k < exceptions.length; k++) {
324 sb.append(exceptions[k].getName());
325 if (k < (exceptions.length - 1))
330 return sb.toString();
331 } catch (Exception e) {
332 return "<" + e + ">";
337 * Returns a string describing this {@code Method}, including
338 * type parameters. The string is formatted as the method access
339 * modifiers, if any, followed by an angle-bracketed
340 * comma-separated list of the method's type parameters, if any,
341 * followed by the method's generic return type, followed by a
342 * space, followed by the class declaring the method, followed by
343 * a period, followed by the method name, followed by a
344 * parenthesized, comma-separated list of the method's generic
345 * formal parameter types.
347 * If this method was declared to take a variable number of
348 * arguments, instead of denoting the last parameter as
349 * "<tt><i>Type</i>[]</tt>", it is denoted as
350 * "<tt><i>Type</i>...</tt>".
352 * A space is used to separate access modifiers from one another
353 * and from the type parameters or return type. If there are no
354 * type parameters, the type parameter list is elided; if the type
355 * parameter list is present, a space separates the list from the
356 * class name. If the method is declared to throw exceptions, the
357 * parameter list is followed by a space, followed by the word
358 * throws followed by a comma-separated list of the generic thrown
359 * exception types. If there are no type parameters, the type
360 * parameter list is elided.
362 * <p>The access modifiers are placed in canonical order as
363 * specified by "The Java Language Specification". This is
364 * {@code public}, {@code protected} or {@code private} first,
365 * and then other modifiers in the following order:
366 * {@code abstract}, {@code static}, {@code final},
367 * {@code synchronized}, {@code native}, {@code strictfp}.
369 * @return a string describing this {@code Method},
370 * include type parameters
374 public String toGenericString() {
376 StringBuilder sb = new StringBuilder();
377 int mod = getModifiers() & Modifier.methodModifiers();
379 sb.append(Modifier.toString(mod)).append(' ');
381 TypeVariable<?>[] typeparms = getTypeParameters();
382 if (typeparms.length > 0) {
383 boolean first = true;
385 for(TypeVariable<?> typeparm: typeparms) {
388 // Class objects can't occur here; no need to test
389 // and call Class.getName().
390 sb.append(typeparm.toString());
396 Type genRetType = getGenericReturnType();
397 sb.append( ((genRetType instanceof Class<?>)?
398 Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
401 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
402 sb.append(getName()).append('(');
403 Type[] params = getGenericParameterTypes();
404 for (int j = 0; j < params.length; j++) {
405 String param = (params[j] instanceof Class)?
406 Field.getTypeName((Class)params[j]):
407 (params[j].toString());
408 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
409 param = param.replaceFirst("\\[\\]$", "...");
411 if (j < (params.length - 1))
415 Type[] exceptions = getGenericExceptionTypes();
416 if (exceptions.length > 0) {
417 sb.append(" throws ");
418 for (int k = 0; k < exceptions.length; k++) {
419 sb.append((exceptions[k] instanceof Class)?
420 ((Class)exceptions[k]).getName():
421 exceptions[k].toString());
422 if (k < (exceptions.length - 1))
426 return sb.toString();
427 } catch (Exception e) {
428 return "<" + e + ">";
433 * Invokes the underlying method represented by this {@code Method}
434 * object, on the specified object with the specified parameters.
435 * Individual parameters are automatically unwrapped to match
436 * primitive formal parameters, and both primitive and reference
437 * parameters are subject to method invocation conversions as
440 * <p>If the underlying method is static, then the specified {@code obj}
441 * argument is ignored. It may be null.
443 * <p>If the number of formal parameters required by the underlying method is
444 * 0, the supplied {@code args} array may be of length 0 or null.
446 * <p>If the underlying method is an instance method, it is invoked
447 * using dynamic method lookup as documented in The Java Language
448 * Specification, Second Edition, section 15.12.4.4; in particular,
449 * overriding based on the runtime type of the target object will occur.
451 * <p>If the underlying method is static, the class that declared
452 * the method is initialized if it has not already been initialized.
454 * <p>If the method completes normally, the value it returns is
455 * returned to the caller of invoke; if the value has a primitive
456 * type, it is first appropriately wrapped in an object. However,
457 * if the value has the type of an array of a primitive type, the
458 * elements of the array are <i>not</i> wrapped in objects; in
459 * other words, an array of primitive type is returned. If the
460 * underlying method return type is void, the invocation returns
463 * @param obj the object the underlying method is invoked from
464 * @param args the arguments used for the method call
465 * @return the result of dispatching the method represented by
466 * this object on {@code obj} with parameters
469 * @exception IllegalAccessException if this {@code Method} object
470 * is enforcing Java language access control and the underlying
471 * method is inaccessible.
472 * @exception IllegalArgumentException if the method is an
473 * instance method and the specified object argument
474 * is not an instance of the class or interface
475 * declaring the underlying method (or of a subclass
476 * or implementor thereof); if the number of actual
477 * and formal parameters differ; if an unwrapping
478 * conversion for primitive arguments fails; or if,
479 * after possible unwrapping, a parameter value
480 * cannot be converted to the corresponding formal
481 * parameter type by a method invocation conversion.
482 * @exception InvocationTargetException if the underlying method
483 * throws an exception.
484 * @exception NullPointerException if the specified object is null
485 * and the method is an instance method.
486 * @exception ExceptionInInitializerError if the initialization
487 * provoked by this method fails.
489 @JavaScriptBody(args = { "method", "self", "args" }, body =
490 "if (args.length > 0) throw 'unsupported now';"
491 + "return method.fld_data(self);"
493 public Object invoke(Object obj, Object... args)
494 throws IllegalAccessException, IllegalArgumentException,
495 InvocationTargetException
497 throw new UnsupportedOperationException();
501 * Returns {@code true} if this method is a bridge
502 * method; returns {@code false} otherwise.
504 * @return true if and only if this method is a bridge
505 * method as defined by the Java Language Specification.
508 public boolean isBridge() {
509 return (getModifiers() & Modifier.BRIDGE) != 0;
513 * Returns {@code true} if this method was declared to take
514 * a variable number of arguments; returns {@code false}
517 * @return {@code true} if an only if this method was declared to
518 * take a variable number of arguments.
521 public boolean isVarArgs() {
522 return (getModifiers() & Modifier.VARARGS) != 0;
526 * Returns {@code true} if this method is a synthetic
527 * method; returns {@code false} otherwise.
529 * @return true if and only if this method is a synthetic
530 * method as defined by the Java Language Specification.
533 public boolean isSynthetic() {
534 return Modifier.isSynthetic(getModifiers());
538 * @throws NullPointerException {@inheritDoc}
541 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
542 if (annotationClass == null)
543 throw new NullPointerException();
545 throw new UnsupportedOperationException();
551 public Annotation[] getDeclaredAnnotations() {
552 throw new UnsupportedOperationException();
556 * Returns the default value for the annotation member represented by
557 * this {@code Method} instance. If the member is of a primitive type,
558 * an instance of the corresponding wrapper type is returned. Returns
559 * null if no default is associated with the member, or if the method
560 * instance does not represent a declared member of an annotation type.
562 * @return the default value for the annotation member represented
563 * by this {@code Method} instance.
564 * @throws TypeNotPresentException if the annotation is of type
565 * {@link Class} and no definition can be found for the
566 * default class value.
569 public Object getDefaultValue() {
570 throw new UnsupportedOperationException();
574 * Returns an array of arrays that represent the annotations on the formal
575 * parameters, in declaration order, of the method represented by
576 * this {@code Method} object. (Returns an array of length zero if the
577 * underlying method is parameterless. If the method has one or more
578 * parameters, a nested array of length zero is returned for each parameter
579 * with no annotations.) The annotation objects contained in the returned
580 * arrays are serializable. The caller of this method is free to modify
581 * the returned arrays; it will have no effect on the arrays returned to
584 * @return an array of arrays that represent the annotations on the formal
585 * parameters, in declaration order, of the method represented by this
589 public Annotation[][] getParameterAnnotations() {
590 throw new UnsupportedOperationException();
594 // bck2brwsr implementation
597 @JavaScriptBody(args = { "clazz", "name", "params" },
598 body = "if (params.length > 0) return null;\n"
599 + "var c = clazz.cnstr.prototype;"
600 + "var prefix = name + '__';\n"
602 + " if (m.indexOf(prefix) === 0) {"
608 private static native Object findMethodData(
609 Class<?> clazz, String name, Class<?>... parameterTypes
612 // XXX should not be public
613 public static Method findMethod(
614 Class<?> clazz, String name, Class<?>... parameterTypes
616 Object data = findMethodData(clazz, name, parameterTypes);
620 return new Method(clazz, name, data);