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;
30 import org.apidesign.bck2brwsr.emul.AnnotationImpl;
33 * A {@code Method} provides information about, and access to, a single method
34 * on a class or interface. The reflected method may be a class method
35 * or an instance method (including an abstract method).
37 * <p>A {@code Method} permits widening conversions to occur when matching the
38 * actual parameters to invoke with the underlying method's formal
39 * parameters, but it throws an {@code IllegalArgumentException} if a
40 * narrowing conversion would occur.
43 * @see java.lang.Class
44 * @see java.lang.Class#getMethods()
45 * @see java.lang.Class#getMethod(String, Class[])
46 * @see java.lang.Class#getDeclaredMethods()
47 * @see java.lang.Class#getDeclaredMethod(String, Class[])
49 * @author Kenneth Russell
50 * @author Nakul Saraiya
53 class Method extends AccessibleObject implements GenericDeclaration,
55 private final Class<?> clazz;
56 private final String name;
57 private final Object data;
58 private final String sig;
59 private int modifiers;
61 // Generics infrastructure
63 private String getGenericSignature() {return null;}
66 * Package-private constructor used by ReflectAccess to enable
67 * instantiation of these objects in Java code from the java.lang
68 * package via sun.reflect.LangReflectAccess.
70 Method(Class<?> declaringClass, String name, Object data, String sig)
72 this.clazz = declaringClass;
79 * Package-private routine (exposed to java.lang.Class via
80 * ReflectAccess) which returns a copy of this Method. The copy's
81 * "root" field points to this Method.
88 * Returns the {@code Class} object representing the class or interface
89 * that declares the method represented by this {@code Method} object.
91 public Class<?> getDeclaringClass() {
96 * Returns the name of the method represented by this {@code Method}
97 * object, as a {@code String}.
99 public String getName() {
104 * Returns the Java language modifiers for the method represented
105 * by this {@code Method} object, as an integer. The {@code Modifier} class should
106 * be used to decode the modifiers.
110 public int getModifiers() {
115 * Returns an array of {@code TypeVariable} objects that represent the
116 * type variables declared by the generic declaration represented by this
117 * {@code GenericDeclaration} object, in declaration order. Returns an
118 * array of length 0 if the underlying generic declaration declares no type
121 * @return an array of {@code TypeVariable} objects that represent
122 * the type variables declared by this generic declaration
123 * @throws GenericSignatureFormatError if the generic
124 * signature of this generic declaration does not conform to
125 * the format specified in
126 * <cite>The Java™ Virtual Machine Specification</cite>
129 public TypeVariable<Method>[] getTypeParameters() {
130 throw new UnsupportedOperationException();
134 * Returns a {@code Class} object that represents the formal return type
135 * of the method represented by this {@code Method} object.
137 * @return the return type for the method this object represents
139 public Class<?> getReturnType() {
140 throw new UnsupportedOperationException();
144 * Returns a {@code Type} object that represents the formal return
145 * type of the method represented by this {@code Method} object.
147 * <p>If the return type is a parameterized type,
148 * the {@code Type} object returned must accurately reflect
149 * the actual type parameters used in the source code.
151 * <p>If the return type is a type variable or a parameterized type, it
152 * is created. Otherwise, it is resolved.
154 * @return a {@code Type} object that represents the formal return
155 * type of the underlying method
156 * @throws GenericSignatureFormatError
157 * if the generic method signature does not conform to the format
159 * <cite>The Java™ Virtual Machine Specification</cite>
160 * @throws TypeNotPresentException if the underlying method's
161 * return type refers to a non-existent type declaration
162 * @throws MalformedParameterizedTypeException if the
163 * underlying method's return typed refers to a parameterized
164 * type that cannot be instantiated for any reason
167 public Type getGenericReturnType() {
168 throw new UnsupportedOperationException();
173 * Returns an array of {@code Class} objects that represent the formal
174 * parameter types, in declaration order, of the method
175 * represented by this {@code Method} object. Returns an array of length
176 * 0 if the underlying method takes no parameters.
178 * @return the parameter types for the method this object
181 public Class<?>[] getParameterTypes() {
182 throw new UnsupportedOperationException();
183 //return (Class<?>[]) parameterTypes.clone();
187 * Returns an array of {@code Type} objects that represent the formal
188 * parameter types, in declaration order, of the method represented by
189 * this {@code Method} object. Returns an array of length 0 if the
190 * underlying method takes no parameters.
192 * <p>If a formal parameter type is a parameterized type,
193 * the {@code Type} object returned for it must accurately reflect
194 * the actual type parameters used in the source code.
196 * <p>If a formal parameter type is a type variable or a parameterized
197 * type, it is created. Otherwise, it is resolved.
199 * @return an array of Types that represent the formal
200 * parameter types of the underlying method, in declaration order
201 * @throws GenericSignatureFormatError
202 * if the generic method signature does not conform to the format
204 * <cite>The Java™ Virtual Machine Specification</cite>
205 * @throws TypeNotPresentException if any of the parameter
206 * types of the underlying method refers to a non-existent type
208 * @throws MalformedParameterizedTypeException if any of
209 * the underlying method's parameter types refer to a parameterized
210 * type that cannot be instantiated for any reason
213 public Type[] getGenericParameterTypes() {
214 throw new UnsupportedOperationException();
219 * Returns an array of {@code Class} objects that represent
220 * the types of the exceptions declared to be thrown
221 * by the underlying method
222 * represented by this {@code Method} object. Returns an array of length
223 * 0 if the method declares no exceptions in its {@code throws} clause.
225 * @return the exception types declared as being thrown by the
226 * method this object represents
228 public Class<?>[] getExceptionTypes() {
229 throw new UnsupportedOperationException();
230 //return (Class<?>[]) exceptionTypes.clone();
234 * Returns an array of {@code Type} objects that represent the
235 * exceptions declared to be thrown by this {@code Method} object.
236 * Returns an array of length 0 if the underlying method declares
237 * no exceptions in its {@code throws} clause.
239 * <p>If an exception type is a type variable or a parameterized
240 * type, it is created. Otherwise, it is resolved.
242 * @return an array of Types that represent the exception types
243 * thrown by the underlying method
244 * @throws GenericSignatureFormatError
245 * if the generic method signature does not conform to the format
247 * <cite>The Java™ Virtual Machine Specification</cite>
248 * @throws TypeNotPresentException if the underlying method's
249 * {@code throws} clause refers to a non-existent type declaration
250 * @throws MalformedParameterizedTypeException if
251 * the underlying method's {@code throws} clause refers to a
252 * parameterized type that cannot be instantiated for any reason
255 public Type[] getGenericExceptionTypes() {
256 throw new UnsupportedOperationException();
260 * Compares this {@code Method} against the specified object. Returns
261 * true if the objects are the same. Two {@code Methods} are the same if
262 * they were declared by the same class and have the same name
263 * and formal parameter types and return type.
265 public boolean equals(Object obj) {
266 if (obj != null && obj instanceof Method) {
267 Method other = (Method)obj;
268 return data == other.data;
274 * Returns a hashcode for this {@code Method}. The hashcode is computed
275 * as the exclusive-or of the hashcodes for the underlying
276 * method's declaring class name and the method's name.
278 public int hashCode() {
279 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
283 * Returns a string describing this {@code Method}. The string is
284 * formatted as the method access modifiers, if any, followed by
285 * the method return type, followed by a space, followed by the
286 * class declaring the method, followed by a period, followed by
287 * the method name, followed by a parenthesized, comma-separated
288 * list of the method's formal parameter types. If the method
289 * throws checked exceptions, the parameter list is followed by a
290 * space, followed by the word throws followed by a
291 * comma-separated list of the thrown exception types.
294 * public boolean java.lang.Object.equals(java.lang.Object)
297 * <p>The access modifiers are placed in canonical order as
298 * specified by "The Java Language Specification". This is
299 * {@code public}, {@code protected} or {@code private} first,
300 * and then other modifiers in the following order:
301 * {@code abstract}, {@code static}, {@code final},
302 * {@code synchronized}, {@code native}, {@code strictfp}.
304 public String toString() {
306 StringBuilder sb = new StringBuilder();
307 int mod = getModifiers() & Modifier.methodModifiers();
309 sb.append(Modifier.toString(mod)).append(' ');
311 sb.append(Field.getTypeName(getReturnType())).append(' ');
312 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
313 sb.append(getName()).append('(');
315 Class<?>[] params = parameterTypes; // avoid clone
316 for (int j = 0; j < params.length; j++) {
317 sb.append(Field.getTypeName(params[j]));
318 if (j < (params.length - 1))
322 Class<?>[] exceptions = exceptionTypes; // avoid clone
323 if (exceptions.length > 0) {
324 sb.append(" throws ");
325 for (int k = 0; k < exceptions.length; k++) {
326 sb.append(exceptions[k].getName());
327 if (k < (exceptions.length - 1))
332 return sb.toString();
333 } catch (Exception e) {
334 return "<" + e + ">";
339 * Returns a string describing this {@code Method}, including
340 * type parameters. The string is formatted as the method access
341 * modifiers, if any, followed by an angle-bracketed
342 * comma-separated list of the method's type parameters, if any,
343 * followed by the method's generic return type, followed by a
344 * space, followed by the class declaring the method, followed by
345 * a period, followed by the method name, followed by a
346 * parenthesized, comma-separated list of the method's generic
347 * formal parameter types.
349 * If this method was declared to take a variable number of
350 * arguments, instead of denoting the last parameter as
351 * "<tt><i>Type</i>[]</tt>", it is denoted as
352 * "<tt><i>Type</i>...</tt>".
354 * A space is used to separate access modifiers from one another
355 * and from the type parameters or return type. If there are no
356 * type parameters, the type parameter list is elided; if the type
357 * parameter list is present, a space separates the list from the
358 * class name. If the method is declared to throw exceptions, the
359 * parameter list is followed by a space, followed by the word
360 * throws followed by a comma-separated list of the generic thrown
361 * exception types. If there are no type parameters, the type
362 * parameter list is elided.
364 * <p>The access modifiers are placed in canonical order as
365 * specified by "The Java Language Specification". This is
366 * {@code public}, {@code protected} or {@code private} first,
367 * and then other modifiers in the following order:
368 * {@code abstract}, {@code static}, {@code final},
369 * {@code synchronized}, {@code native}, {@code strictfp}.
371 * @return a string describing this {@code Method},
372 * include type parameters
376 public String toGenericString() {
378 StringBuilder sb = new StringBuilder();
379 int mod = getModifiers() & Modifier.methodModifiers();
381 sb.append(Modifier.toString(mod)).append(' ');
383 TypeVariable<?>[] typeparms = getTypeParameters();
384 if (typeparms.length > 0) {
385 boolean first = true;
387 for(TypeVariable<?> typeparm: typeparms) {
390 // Class objects can't occur here; no need to test
391 // and call Class.getName().
392 sb.append(typeparm.toString());
398 Type genRetType = getGenericReturnType();
399 sb.append( ((genRetType instanceof Class<?>)?
400 Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
403 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
404 sb.append(getName()).append('(');
405 Type[] params = getGenericParameterTypes();
406 for (int j = 0; j < params.length; j++) {
407 String param = (params[j] instanceof Class)?
408 Field.getTypeName((Class)params[j]):
409 (params[j].toString());
410 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
411 param = param.replaceFirst("\\[\\]$", "...");
413 if (j < (params.length - 1))
417 Type[] exceptions = getGenericExceptionTypes();
418 if (exceptions.length > 0) {
419 sb.append(" throws ");
420 for (int k = 0; k < exceptions.length; k++) {
421 sb.append((exceptions[k] instanceof Class)?
422 ((Class)exceptions[k]).getName():
423 exceptions[k].toString());
424 if (k < (exceptions.length - 1))
428 return sb.toString();
429 } catch (Exception e) {
430 return "<" + e + ">";
435 * Invokes the underlying method represented by this {@code Method}
436 * object, on the specified object with the specified parameters.
437 * Individual parameters are automatically unwrapped to match
438 * primitive formal parameters, and both primitive and reference
439 * parameters are subject to method invocation conversions as
442 * <p>If the underlying method is static, then the specified {@code obj}
443 * argument is ignored. It may be null.
445 * <p>If the number of formal parameters required by the underlying method is
446 * 0, the supplied {@code args} array may be of length 0 or null.
448 * <p>If the underlying method is an instance method, it is invoked
449 * using dynamic method lookup as documented in The Java Language
450 * Specification, Second Edition, section 15.12.4.4; in particular,
451 * overriding based on the runtime type of the target object will occur.
453 * <p>If the underlying method is static, the class that declared
454 * the method is initialized if it has not already been initialized.
456 * <p>If the method completes normally, the value it returns is
457 * returned to the caller of invoke; if the value has a primitive
458 * type, it is first appropriately wrapped in an object. However,
459 * if the value has the type of an array of a primitive type, the
460 * elements of the array are <i>not</i> wrapped in objects; in
461 * other words, an array of primitive type is returned. If the
462 * underlying method return type is void, the invocation returns
465 * @param obj the object the underlying method is invoked from
466 * @param args the arguments used for the method call
467 * @return the result of dispatching the method represented by
468 * this object on {@code obj} with parameters
471 * @exception IllegalAccessException if this {@code Method} object
472 * is enforcing Java language access control and the underlying
473 * method is inaccessible.
474 * @exception IllegalArgumentException if the method is an
475 * instance method and the specified object argument
476 * is not an instance of the class or interface
477 * declaring the underlying method (or of a subclass
478 * or implementor thereof); if the number of actual
479 * and formal parameters differ; if an unwrapping
480 * conversion for primitive arguments fails; or if,
481 * after possible unwrapping, a parameter value
482 * cannot be converted to the corresponding formal
483 * parameter type by a method invocation conversion.
484 * @exception InvocationTargetException if the underlying method
485 * throws an exception.
486 * @exception NullPointerException if the specified object is null
487 * and the method is an instance method.
488 * @exception ExceptionInInitializerError if the initialization
489 * provoked by this method fails.
491 @JavaScriptBody(args = { "method", "self", "args" }, body =
492 "if (args.length > 0) throw 'unsupported now';"
493 + "return method.fld_data(self);"
495 public Object invoke(Object obj, Object... args)
496 throws IllegalAccessException, IllegalArgumentException,
497 InvocationTargetException
499 throw new UnsupportedOperationException();
503 * Returns {@code true} if this method is a bridge
504 * method; returns {@code false} otherwise.
506 * @return true if and only if this method is a bridge
507 * method as defined by the Java Language Specification.
510 public boolean isBridge() {
511 return (getModifiers() & Modifier.BRIDGE) != 0;
515 * Returns {@code true} if this method was declared to take
516 * a variable number of arguments; returns {@code false}
519 * @return {@code true} if an only if this method was declared to
520 * take a variable number of arguments.
523 public boolean isVarArgs() {
524 return (getModifiers() & Modifier.VARARGS) != 0;
528 * Returns {@code true} if this method is a synthetic
529 * method; returns {@code false} otherwise.
531 * @return true if and only if this method is a synthetic
532 * method as defined by the Java Language Specification.
535 public boolean isSynthetic() {
536 return Modifier.isSynthetic(getModifiers());
539 @JavaScriptBody(args = { "self", "ac" },
541 "if (self.fld_data.anno) {"
542 + " return self.fld_data.anno['L' + ac.jvmName + ';'];"
543 + "} else return null;"
545 private Object getAnnotationData(Class<?> annotationClass) {
546 throw new UnsupportedOperationException();
550 * @throws NullPointerException {@inheritDoc}
553 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
554 Object data = getAnnotationData(annotationClass);
555 return data == null ? null : AnnotationImpl.create(annotationClass, data);
561 public Annotation[] getDeclaredAnnotations() {
562 throw new UnsupportedOperationException();
566 * Returns the default value for the annotation member represented by
567 * this {@code Method} instance. If the member is of a primitive type,
568 * an instance of the corresponding wrapper type is returned. Returns
569 * null if no default is associated with the member, or if the method
570 * instance does not represent a declared member of an annotation type.
572 * @return the default value for the annotation member represented
573 * by this {@code Method} instance.
574 * @throws TypeNotPresentException if the annotation is of type
575 * {@link Class} and no definition can be found for the
576 * default class value.
579 public Object getDefaultValue() {
580 throw new UnsupportedOperationException();
584 * Returns an array of arrays that represent the annotations on the formal
585 * parameters, in declaration order, of the method represented by
586 * this {@code Method} object. (Returns an array of length zero if the
587 * underlying method is parameterless. If the method has one or more
588 * parameters, a nested array of length zero is returned for each parameter
589 * with no annotations.) The annotation objects contained in the returned
590 * arrays are serializable. The caller of this method is free to modify
591 * the returned arrays; it will have no effect on the arrays returned to
594 * @return an array of arrays that represent the annotations on the formal
595 * parameters, in declaration order, of the method represented by this
599 public Annotation[][] getParameterAnnotations() {
600 throw new UnsupportedOperationException();
604 // bck2brwsr implementation
607 @JavaScriptBody(args = { "clazz", "prefix" },
609 + "var c = clazz.cnstr.prototype;"
610 + "var arr = new Array();\n"
612 + " if (m.indexOf(prefix) === 0) {\n"
614 + " arr.push(c[m]);\n"
619 private static native Object[] findMethodData(
620 Class<?> clazz, String prefix
623 // XXX should not be public
624 public static Method findMethod(
625 Class<?> clazz, String name, Class<?>... parameterTypes
627 Object[] data = findMethodData(clazz, name + "__");
628 if (data.length == 0) {
631 String sig = ((String)data[0]).substring(name.length() + 2);
632 return new Method(clazz, name, data[1], sig);
635 public static Method[] findMethods(Class<?> clazz) {
636 Object[] namesAndData = findMethodData(clazz, "");
638 for (int i = 0; i < namesAndData.length; i += 2) {
639 String sig = (String) namesAndData[i];
640 Object data = namesAndData[i + 1];
641 int middle = sig.indexOf("__");
645 String name = sig.substring(0, middle);
646 sig = sig.substring(middle + 2);
647 namesAndData[cnt++] = new Method(clazz, name, data, sig);
649 Method[] arr = new Method[cnt];
650 for (int i = 0; i < cnt; i++) {
651 arr[i] = (Method)namesAndData[i];