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 final String sig;
58 private int modifiers;
60 // Generics infrastructure
62 private String getGenericSignature() {return null;}
65 * Package-private constructor used by ReflectAccess to enable
66 * instantiation of these objects in Java code from the java.lang
67 * package via sun.reflect.LangReflectAccess.
69 Method(Class<?> declaringClass, String name, Object data, String sig)
71 this.clazz = declaringClass;
78 * Package-private routine (exposed to java.lang.Class via
79 * ReflectAccess) which returns a copy of this Method. The copy's
80 * "root" field points to this Method.
87 * Returns the {@code Class} object representing the class or interface
88 * that declares the method represented by this {@code Method} object.
90 public Class<?> getDeclaringClass() {
95 * Returns the name of the method represented by this {@code Method}
96 * object, as a {@code String}.
98 public String getName() {
103 * Returns the Java language modifiers for the method represented
104 * by this {@code Method} object, as an integer. The {@code Modifier} class should
105 * be used to decode the modifiers.
109 public int getModifiers() {
114 * Returns an array of {@code TypeVariable} objects that represent the
115 * type variables declared by the generic declaration represented by this
116 * {@code GenericDeclaration} object, in declaration order. Returns an
117 * array of length 0 if the underlying generic declaration declares no type
120 * @return an array of {@code TypeVariable} objects that represent
121 * the type variables declared by this generic declaration
122 * @throws GenericSignatureFormatError if the generic
123 * signature of this generic declaration does not conform to
124 * the format specified in
125 * <cite>The Java™ Virtual Machine Specification</cite>
128 public TypeVariable<Method>[] getTypeParameters() {
129 throw new UnsupportedOperationException();
133 * Returns a {@code Class} object that represents the formal return type
134 * of the method represented by this {@code Method} object.
136 * @return the return type for the method this object represents
138 public Class<?> getReturnType() {
139 throw new UnsupportedOperationException();
143 * Returns a {@code Type} object that represents the formal return
144 * type of the method represented by this {@code Method} object.
146 * <p>If the return type is a parameterized type,
147 * the {@code Type} object returned must accurately reflect
148 * the actual type parameters used in the source code.
150 * <p>If the return type is a type variable or a parameterized type, it
151 * is created. Otherwise, it is resolved.
153 * @return a {@code Type} object that represents the formal return
154 * type of the underlying method
155 * @throws GenericSignatureFormatError
156 * if the generic method signature does not conform to the format
158 * <cite>The Java™ Virtual Machine Specification</cite>
159 * @throws TypeNotPresentException if the underlying method's
160 * return type refers to a non-existent type declaration
161 * @throws MalformedParameterizedTypeException if the
162 * underlying method's return typed refers to a parameterized
163 * type that cannot be instantiated for any reason
166 public Type getGenericReturnType() {
167 throw new UnsupportedOperationException();
172 * Returns an array of {@code Class} objects that represent the formal
173 * parameter types, in declaration order, of the method
174 * represented by this {@code Method} object. Returns an array of length
175 * 0 if the underlying method takes no parameters.
177 * @return the parameter types for the method this object
180 public Class<?>[] getParameterTypes() {
181 throw new UnsupportedOperationException();
182 //return (Class<?>[]) parameterTypes.clone();
186 * Returns an array of {@code Type} objects that represent the formal
187 * parameter types, in declaration order, of the method represented by
188 * this {@code Method} object. Returns an array of length 0 if the
189 * underlying method takes no parameters.
191 * <p>If a formal parameter type is a parameterized type,
192 * the {@code Type} object returned for it must accurately reflect
193 * the actual type parameters used in the source code.
195 * <p>If a formal parameter type is a type variable or a parameterized
196 * type, it is created. Otherwise, it is resolved.
198 * @return an array of Types that represent the formal
199 * parameter types of the underlying method, in declaration order
200 * @throws GenericSignatureFormatError
201 * if the generic method signature does not conform to the format
203 * <cite>The Java™ Virtual Machine Specification</cite>
204 * @throws TypeNotPresentException if any of the parameter
205 * types of the underlying method refers to a non-existent type
207 * @throws MalformedParameterizedTypeException if any of
208 * the underlying method's parameter types refer to a parameterized
209 * type that cannot be instantiated for any reason
212 public Type[] getGenericParameterTypes() {
213 throw new UnsupportedOperationException();
218 * Returns an array of {@code Class} objects that represent
219 * the types of the exceptions declared to be thrown
220 * by the underlying method
221 * represented by this {@code Method} object. Returns an array of length
222 * 0 if the method declares no exceptions in its {@code throws} clause.
224 * @return the exception types declared as being thrown by the
225 * method this object represents
227 public Class<?>[] getExceptionTypes() {
228 throw new UnsupportedOperationException();
229 //return (Class<?>[]) exceptionTypes.clone();
233 * Returns an array of {@code Type} objects that represent the
234 * exceptions declared to be thrown by this {@code Method} object.
235 * Returns an array of length 0 if the underlying method declares
236 * no exceptions in its {@code throws} clause.
238 * <p>If an exception type is a type variable or a parameterized
239 * type, it is created. Otherwise, it is resolved.
241 * @return an array of Types that represent the exception types
242 * thrown by the underlying method
243 * @throws GenericSignatureFormatError
244 * if the generic method signature does not conform to the format
246 * <cite>The Java™ Virtual Machine Specification</cite>
247 * @throws TypeNotPresentException if the underlying method's
248 * {@code throws} clause refers to a non-existent type declaration
249 * @throws MalformedParameterizedTypeException if
250 * the underlying method's {@code throws} clause refers to a
251 * parameterized type that cannot be instantiated for any reason
254 public Type[] getGenericExceptionTypes() {
255 throw new UnsupportedOperationException();
259 * Compares this {@code Method} against the specified object. Returns
260 * true if the objects are the same. Two {@code Methods} are the same if
261 * they were declared by the same class and have the same name
262 * and formal parameter types and return type.
264 public boolean equals(Object obj) {
265 if (obj != null && obj instanceof Method) {
266 Method other = (Method)obj;
267 return data == other.data;
273 * Returns a hashcode for this {@code Method}. The hashcode is computed
274 * as the exclusive-or of the hashcodes for the underlying
275 * method's declaring class name and the method's name.
277 public int hashCode() {
278 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
282 * Returns a string describing this {@code Method}. The string is
283 * formatted as the method access modifiers, if any, followed by
284 * the method return type, followed by a space, followed by the
285 * class declaring the method, followed by a period, followed by
286 * the method name, followed by a parenthesized, comma-separated
287 * list of the method's formal parameter types. If the method
288 * throws checked exceptions, the parameter list is followed by a
289 * space, followed by the word throws followed by a
290 * comma-separated list of the thrown exception types.
293 * public boolean java.lang.Object.equals(java.lang.Object)
296 * <p>The access modifiers are placed in canonical order as
297 * specified by "The Java Language Specification". This is
298 * {@code public}, {@code protected} or {@code private} first,
299 * and then other modifiers in the following order:
300 * {@code abstract}, {@code static}, {@code final},
301 * {@code synchronized}, {@code native}, {@code strictfp}.
303 public String toString() {
305 StringBuilder sb = new StringBuilder();
306 int mod = getModifiers() & Modifier.methodModifiers();
308 sb.append(Modifier.toString(mod)).append(' ');
310 sb.append(Field.getTypeName(getReturnType())).append(' ');
311 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
312 sb.append(getName()).append('(');
314 Class<?>[] params = parameterTypes; // avoid clone
315 for (int j = 0; j < params.length; j++) {
316 sb.append(Field.getTypeName(params[j]));
317 if (j < (params.length - 1))
321 Class<?>[] exceptions = exceptionTypes; // avoid clone
322 if (exceptions.length > 0) {
323 sb.append(" throws ");
324 for (int k = 0; k < exceptions.length; k++) {
325 sb.append(exceptions[k].getName());
326 if (k < (exceptions.length - 1))
331 return sb.toString();
332 } catch (Exception e) {
333 return "<" + e + ">";
338 * Returns a string describing this {@code Method}, including
339 * type parameters. The string is formatted as the method access
340 * modifiers, if any, followed by an angle-bracketed
341 * comma-separated list of the method's type parameters, if any,
342 * followed by the method's generic return type, followed by a
343 * space, followed by the class declaring the method, followed by
344 * a period, followed by the method name, followed by a
345 * parenthesized, comma-separated list of the method's generic
346 * formal parameter types.
348 * If this method was declared to take a variable number of
349 * arguments, instead of denoting the last parameter as
350 * "<tt><i>Type</i>[]</tt>", it is denoted as
351 * "<tt><i>Type</i>...</tt>".
353 * A space is used to separate access modifiers from one another
354 * and from the type parameters or return type. If there are no
355 * type parameters, the type parameter list is elided; if the type
356 * parameter list is present, a space separates the list from the
357 * class name. If the method is declared to throw exceptions, the
358 * parameter list is followed by a space, followed by the word
359 * throws followed by a comma-separated list of the generic thrown
360 * exception types. If there are no type parameters, the type
361 * parameter list is elided.
363 * <p>The access modifiers are placed in canonical order as
364 * specified by "The Java Language Specification". This is
365 * {@code public}, {@code protected} or {@code private} first,
366 * and then other modifiers in the following order:
367 * {@code abstract}, {@code static}, {@code final},
368 * {@code synchronized}, {@code native}, {@code strictfp}.
370 * @return a string describing this {@code Method},
371 * include type parameters
375 public String toGenericString() {
377 StringBuilder sb = new StringBuilder();
378 int mod = getModifiers() & Modifier.methodModifiers();
380 sb.append(Modifier.toString(mod)).append(' ');
382 TypeVariable<?>[] typeparms = getTypeParameters();
383 if (typeparms.length > 0) {
384 boolean first = true;
386 for(TypeVariable<?> typeparm: typeparms) {
389 // Class objects can't occur here; no need to test
390 // and call Class.getName().
391 sb.append(typeparm.toString());
397 Type genRetType = getGenericReturnType();
398 sb.append( ((genRetType instanceof Class<?>)?
399 Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
402 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
403 sb.append(getName()).append('(');
404 Type[] params = getGenericParameterTypes();
405 for (int j = 0; j < params.length; j++) {
406 String param = (params[j] instanceof Class)?
407 Field.getTypeName((Class)params[j]):
408 (params[j].toString());
409 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
410 param = param.replaceFirst("\\[\\]$", "...");
412 if (j < (params.length - 1))
416 Type[] exceptions = getGenericExceptionTypes();
417 if (exceptions.length > 0) {
418 sb.append(" throws ");
419 for (int k = 0; k < exceptions.length; k++) {
420 sb.append((exceptions[k] instanceof Class)?
421 ((Class)exceptions[k]).getName():
422 exceptions[k].toString());
423 if (k < (exceptions.length - 1))
427 return sb.toString();
428 } catch (Exception e) {
429 return "<" + e + ">";
434 * Invokes the underlying method represented by this {@code Method}
435 * object, on the specified object with the specified parameters.
436 * Individual parameters are automatically unwrapped to match
437 * primitive formal parameters, and both primitive and reference
438 * parameters are subject to method invocation conversions as
441 * <p>If the underlying method is static, then the specified {@code obj}
442 * argument is ignored. It may be null.
444 * <p>If the number of formal parameters required by the underlying method is
445 * 0, the supplied {@code args} array may be of length 0 or null.
447 * <p>If the underlying method is an instance method, it is invoked
448 * using dynamic method lookup as documented in The Java Language
449 * Specification, Second Edition, section 15.12.4.4; in particular,
450 * overriding based on the runtime type of the target object will occur.
452 * <p>If the underlying method is static, the class that declared
453 * the method is initialized if it has not already been initialized.
455 * <p>If the method completes normally, the value it returns is
456 * returned to the caller of invoke; if the value has a primitive
457 * type, it is first appropriately wrapped in an object. However,
458 * if the value has the type of an array of a primitive type, the
459 * elements of the array are <i>not</i> wrapped in objects; in
460 * other words, an array of primitive type is returned. If the
461 * underlying method return type is void, the invocation returns
464 * @param obj the object the underlying method is invoked from
465 * @param args the arguments used for the method call
466 * @return the result of dispatching the method represented by
467 * this object on {@code obj} with parameters
470 * @exception IllegalAccessException if this {@code Method} object
471 * is enforcing Java language access control and the underlying
472 * method is inaccessible.
473 * @exception IllegalArgumentException if the method is an
474 * instance method and the specified object argument
475 * is not an instance of the class or interface
476 * declaring the underlying method (or of a subclass
477 * or implementor thereof); if the number of actual
478 * and formal parameters differ; if an unwrapping
479 * conversion for primitive arguments fails; or if,
480 * after possible unwrapping, a parameter value
481 * cannot be converted to the corresponding formal
482 * parameter type by a method invocation conversion.
483 * @exception InvocationTargetException if the underlying method
484 * throws an exception.
485 * @exception NullPointerException if the specified object is null
486 * and the method is an instance method.
487 * @exception ExceptionInInitializerError if the initialization
488 * provoked by this method fails.
490 @JavaScriptBody(args = { "method", "self", "args" }, body =
491 "if (args.length > 0) throw 'unsupported now';"
492 + "return method.fld_data(self);"
494 public Object invoke(Object obj, Object... args)
495 throws IllegalAccessException, IllegalArgumentException,
496 InvocationTargetException
498 throw new UnsupportedOperationException();
502 * Returns {@code true} if this method is a bridge
503 * method; returns {@code false} otherwise.
505 * @return true if and only if this method is a bridge
506 * method as defined by the Java Language Specification.
509 public boolean isBridge() {
510 return (getModifiers() & Modifier.BRIDGE) != 0;
514 * Returns {@code true} if this method was declared to take
515 * a variable number of arguments; returns {@code false}
518 * @return {@code true} if an only if this method was declared to
519 * take a variable number of arguments.
522 public boolean isVarArgs() {
523 return (getModifiers() & Modifier.VARARGS) != 0;
527 * Returns {@code true} if this method is a synthetic
528 * method; returns {@code false} otherwise.
530 * @return true if and only if this method is a synthetic
531 * method as defined by the Java Language Specification.
534 public boolean isSynthetic() {
535 return Modifier.isSynthetic(getModifiers());
539 * @throws NullPointerException {@inheritDoc}
542 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
543 if (annotationClass == null)
544 throw new NullPointerException();
546 throw new UnsupportedOperationException();
552 public Annotation[] getDeclaredAnnotations() {
553 throw new UnsupportedOperationException();
557 * Returns the default value for the annotation member represented by
558 * this {@code Method} instance. If the member is of a primitive type,
559 * an instance of the corresponding wrapper type is returned. Returns
560 * null if no default is associated with the member, or if the method
561 * instance does not represent a declared member of an annotation type.
563 * @return the default value for the annotation member represented
564 * by this {@code Method} instance.
565 * @throws TypeNotPresentException if the annotation is of type
566 * {@link Class} and no definition can be found for the
567 * default class value.
570 public Object getDefaultValue() {
571 throw new UnsupportedOperationException();
575 * Returns an array of arrays that represent the annotations on the formal
576 * parameters, in declaration order, of the method represented by
577 * this {@code Method} object. (Returns an array of length zero if the
578 * underlying method is parameterless. If the method has one or more
579 * parameters, a nested array of length zero is returned for each parameter
580 * with no annotations.) The annotation objects contained in the returned
581 * arrays are serializable. The caller of this method is free to modify
582 * the returned arrays; it will have no effect on the arrays returned to
585 * @return an array of arrays that represent the annotations on the formal
586 * parameters, in declaration order, of the method represented by this
590 public Annotation[][] getParameterAnnotations() {
591 throw new UnsupportedOperationException();
595 // bck2brwsr implementation
598 @JavaScriptBody(args = { "clazz", "prefix" },
600 + "var c = clazz.cnstr.prototype;"
601 + "var arr = new Array();\n"
603 + " if (m.indexOf(prefix) === 0) {\n"
605 + " arr.push(c[m]);\n"
610 private static native Object[] findMethodData(
611 Class<?> clazz, String prefix
614 // XXX should not be public
615 public static Method findMethod(
616 Class<?> clazz, String name, Class<?>... parameterTypes
618 Object[] data = findMethodData(clazz, name + "__");
619 if (data.length == 0) {
622 String sig = ((String)data[0]).substring(name.length() + 2);
623 return new Method(clazz, name, data[1], sig);
626 public static Method[] findMethods(Class<?> clazz) {
627 Object[] namesAndData = findMethodData(clazz, "");
629 for (int i = 0; i < namesAndData.length; i += 2) {
630 String sig = (String) namesAndData[i];
631 Object data = namesAndData[i + 1];
632 int middle = sig.indexOf("__");
636 String name = sig.substring(0, middle);
637 sig = sig.substring(middle + 2);
638 namesAndData[cnt++] = new Method(clazz, name, data, sig);
640 Method[] arr = new Method[cnt];
641 for (int i = 0; i < cnt; i++) {
642 arr[i] = (Method)namesAndData[i];