Making sure parameters for non-static method invoked by reflection are correct.
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 java.util.Enumeration;
30 import org.apidesign.bck2brwsr.core.JavaScriptBody;
31 import org.apidesign.bck2brwsr.emul.reflect.AnnotationImpl;
32 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
35 * A {@code Method} provides information about, and access to, a single method
36 * on a class or interface. The reflected method may be a class method
37 * or an instance method (including an abstract method).
39 * <p>A {@code Method} permits widening conversions to occur when matching the
40 * actual parameters to invoke with the underlying method's formal
41 * parameters, but it throws an {@code IllegalArgumentException} if a
42 * narrowing conversion would occur.
45 * @see java.lang.Class
46 * @see java.lang.Class#getMethods()
47 * @see java.lang.Class#getMethod(String, Class[])
48 * @see java.lang.Class#getDeclaredMethods()
49 * @see java.lang.Class#getDeclaredMethod(String, Class[])
51 * @author Kenneth Russell
52 * @author Nakul Saraiya
55 class Method extends AccessibleObject implements GenericDeclaration,
57 private final Class<?> clazz;
58 private final String name;
59 private final Object data;
60 private final String sig;
62 // Generics infrastructure
64 private String getGenericSignature() {return null;}
67 * Package-private constructor used by ReflectAccess to enable
68 * instantiation of these objects in Java code from the java.lang
69 * package via sun.reflect.LangReflectAccess.
71 Method(Class<?> declaringClass, String name, Object data, String sig)
73 this.clazz = declaringClass;
80 * Package-private routine (exposed to java.lang.Class via
81 * ReflectAccess) which returns a copy of this Method. The copy's
82 * "root" field points to this Method.
89 * Returns the {@code Class} object representing the class or interface
90 * that declares the method represented by this {@code Method} object.
92 public Class<?> getDeclaringClass() {
97 * Returns the name of the method represented by this {@code Method}
98 * object, as a {@code String}.
100 public String getName() {
105 * Returns the Java language modifiers for the method represented
106 * by this {@code Method} object, as an integer. The {@code Modifier} class should
107 * be used to decode the modifiers.
111 public int getModifiers() {
112 return getAccess(data);
115 @JavaScriptBody(args = "self", body = "return self.access;")
116 static native int getAccess(Object self);
119 * Returns an array of {@code TypeVariable} objects that represent the
120 * type variables declared by the generic declaration represented by this
121 * {@code GenericDeclaration} object, in declaration order. Returns an
122 * array of length 0 if the underlying generic declaration declares no type
125 * @return an array of {@code TypeVariable} objects that represent
126 * the type variables declared by this generic declaration
127 * @throws GenericSignatureFormatError if the generic
128 * signature of this generic declaration does not conform to
129 * the format specified in
130 * <cite>The Java™ Virtual Machine Specification</cite>
133 public TypeVariable<Method>[] getTypeParameters() {
134 throw new UnsupportedOperationException();
138 * Returns a {@code Class} object that represents the formal return type
139 * of the method represented by this {@code Method} object.
141 * @return the return type for the method this object represents
143 public Class<?> getReturnType() {
144 return MethodImpl.signatureParser(sig).nextElement();
148 * Returns a {@code Type} object that represents the formal return
149 * type of the method represented by this {@code Method} object.
151 * <p>If the return type is a parameterized type,
152 * the {@code Type} object returned must accurately reflect
153 * the actual type parameters used in the source code.
155 * <p>If the return type is a type variable or a parameterized type, it
156 * is created. Otherwise, it is resolved.
158 * @return a {@code Type} object that represents the formal return
159 * type of the underlying method
160 * @throws GenericSignatureFormatError
161 * if the generic method signature does not conform to the format
163 * <cite>The Java™ Virtual Machine Specification</cite>
164 * @throws TypeNotPresentException if the underlying method's
165 * return type refers to a non-existent type declaration
166 * @throws MalformedParameterizedTypeException if the
167 * underlying method's return typed refers to a parameterized
168 * type that cannot be instantiated for any reason
171 public Type getGenericReturnType() {
172 throw new UnsupportedOperationException();
177 * Returns an array of {@code Class} objects that represent the formal
178 * parameter types, in declaration order, of the method
179 * represented by this {@code Method} object. Returns an array of length
180 * 0 if the underlying method takes no parameters.
182 * @return the parameter types for the method this object
185 public Class<?>[] getParameterTypes() {
186 return getParameterTypes(sig);
189 static Class<?>[] getParameterTypes(String sig) {
190 Class[] arr = new Class[MethodImpl.signatureElements(sig) - 1];
191 Enumeration<Class> en = MethodImpl.signatureParser(sig);
192 en.nextElement(); // return type
193 for (int i = 0; i < arr.length; i++) {
194 arr[i] = en.nextElement();
200 * Returns an array of {@code Type} objects that represent the formal
201 * parameter types, in declaration order, of the method represented by
202 * this {@code Method} object. Returns an array of length 0 if the
203 * underlying method takes no parameters.
205 * <p>If a formal parameter type is a parameterized type,
206 * the {@code Type} object returned for it must accurately reflect
207 * the actual type parameters used in the source code.
209 * <p>If a formal parameter type is a type variable or a parameterized
210 * type, it is created. Otherwise, it is resolved.
212 * @return an array of Types that represent the formal
213 * parameter types of the underlying method, in declaration order
214 * @throws GenericSignatureFormatError
215 * if the generic method signature does not conform to the format
217 * <cite>The Java™ Virtual Machine Specification</cite>
218 * @throws TypeNotPresentException if any of the parameter
219 * types of the underlying method refers to a non-existent type
221 * @throws MalformedParameterizedTypeException if any of
222 * the underlying method's parameter types refer to a parameterized
223 * type that cannot be instantiated for any reason
226 public Type[] getGenericParameterTypes() {
227 throw new UnsupportedOperationException();
232 * Returns an array of {@code Class} objects that represent
233 * the types of the exceptions declared to be thrown
234 * by the underlying method
235 * represented by this {@code Method} object. Returns an array of length
236 * 0 if the method declares no exceptions in its {@code throws} clause.
238 * @return the exception types declared as being thrown by the
239 * method this object represents
241 public Class<?>[] getExceptionTypes() {
246 * Returns an array of {@code Type} objects that represent the
247 * exceptions declared to be thrown by this {@code Method} object.
248 * Returns an array of length 0 if the underlying method declares
249 * no exceptions in its {@code throws} clause.
251 * <p>If an exception type is a type variable or a parameterized
252 * type, it is created. Otherwise, it is resolved.
254 * @return an array of Types that represent the exception types
255 * thrown by the underlying method
256 * @throws GenericSignatureFormatError
257 * if the generic method signature does not conform to the format
259 * <cite>The Java™ Virtual Machine Specification</cite>
260 * @throws TypeNotPresentException if the underlying method's
261 * {@code throws} clause refers to a non-existent type declaration
262 * @throws MalformedParameterizedTypeException if
263 * the underlying method's {@code throws} clause refers to a
264 * parameterized type that cannot be instantiated for any reason
267 public Type[] getGenericExceptionTypes() {
268 throw new UnsupportedOperationException();
272 * Compares this {@code Method} against the specified object. Returns
273 * true if the objects are the same. Two {@code Methods} are the same if
274 * they were declared by the same class and have the same name
275 * and formal parameter types and return type.
277 public boolean equals(Object obj) {
278 if (obj != null && obj instanceof Method) {
279 Method other = (Method)obj;
280 return data == other.data;
286 * Returns a hashcode for this {@code Method}. The hashcode is computed
287 * as the exclusive-or of the hashcodes for the underlying
288 * method's declaring class name and the method's name.
290 public int hashCode() {
291 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
295 * Returns a string describing this {@code Method}. The string is
296 * formatted as the method access modifiers, if any, followed by
297 * the method return type, followed by a space, followed by the
298 * class declaring the method, followed by a period, followed by
299 * the method name, followed by a parenthesized, comma-separated
300 * list of the method's formal parameter types. If the method
301 * throws checked exceptions, the parameter list is followed by a
302 * space, followed by the word throws followed by a
303 * comma-separated list of the thrown exception types.
306 * public boolean java.lang.Object.equals(java.lang.Object)
309 * <p>The access modifiers are placed in canonical order as
310 * specified by "The Java Language Specification". This is
311 * {@code public}, {@code protected} or {@code private} first,
312 * and then other modifiers in the following order:
313 * {@code abstract}, {@code static}, {@code final},
314 * {@code synchronized}, {@code native}, {@code strictfp}.
316 public String toString() {
318 StringBuilder sb = new StringBuilder();
319 int mod = getModifiers() & Modifier.methodModifiers();
321 sb.append(Modifier.toString(mod)).append(' ');
323 sb.append(Field.getTypeName(getReturnType())).append(' ');
324 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
325 sb.append(getName()).append('(');
326 Class<?>[] params = getParameterTypes(); // avoid clone
327 for (int j = 0; j < params.length; j++) {
328 sb.append(Field.getTypeName(params[j]));
329 if (j < (params.length - 1))
334 Class<?>[] exceptions = exceptionTypes; // avoid clone
335 if (exceptions.length > 0) {
336 sb.append(" throws ");
337 for (int k = 0; k < exceptions.length; k++) {
338 sb.append(exceptions[k].getName());
339 if (k < (exceptions.length - 1))
344 return sb.toString();
345 } catch (Exception e) {
346 return "<" + e + ">";
351 * Returns a string describing this {@code Method}, including
352 * type parameters. The string is formatted as the method access
353 * modifiers, if any, followed by an angle-bracketed
354 * comma-separated list of the method's type parameters, if any,
355 * followed by the method's generic return type, followed by a
356 * space, followed by the class declaring the method, followed by
357 * a period, followed by the method name, followed by a
358 * parenthesized, comma-separated list of the method's generic
359 * formal parameter types.
361 * If this method was declared to take a variable number of
362 * arguments, instead of denoting the last parameter as
363 * "<tt><i>Type</i>[]</tt>", it is denoted as
364 * "<tt><i>Type</i>...</tt>".
366 * A space is used to separate access modifiers from one another
367 * and from the type parameters or return type. If there are no
368 * type parameters, the type parameter list is elided; if the type
369 * parameter list is present, a space separates the list from the
370 * class name. If the method is declared to throw exceptions, the
371 * parameter list is followed by a space, followed by the word
372 * throws followed by a comma-separated list of the generic thrown
373 * exception types. If there are no type parameters, the type
374 * parameter list is elided.
376 * <p>The access modifiers are placed in canonical order as
377 * specified by "The Java Language Specification". This is
378 * {@code public}, {@code protected} or {@code private} first,
379 * and then other modifiers in the following order:
380 * {@code abstract}, {@code static}, {@code final},
381 * {@code synchronized}, {@code native}, {@code strictfp}.
383 * @return a string describing this {@code Method},
384 * include type parameters
388 public String toGenericString() {
390 StringBuilder sb = new StringBuilder();
391 int mod = getModifiers() & Modifier.methodModifiers();
393 sb.append(Modifier.toString(mod)).append(' ');
395 TypeVariable<?>[] typeparms = getTypeParameters();
396 if (typeparms.length > 0) {
397 boolean first = true;
399 for(TypeVariable<?> typeparm: typeparms) {
402 // Class objects can't occur here; no need to test
403 // and call Class.getName().
404 sb.append(typeparm.toString());
410 Type genRetType = getGenericReturnType();
411 sb.append( ((genRetType instanceof Class<?>)?
412 Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
415 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
416 sb.append(getName()).append('(');
417 Type[] params = getGenericParameterTypes();
418 for (int j = 0; j < params.length; j++) {
419 String param = (params[j] instanceof Class)?
420 Field.getTypeName((Class)params[j]):
421 (params[j].toString());
422 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
423 param = param.replaceFirst("\\[\\]$", "...");
425 if (j < (params.length - 1))
429 Type[] exceptions = getGenericExceptionTypes();
430 if (exceptions.length > 0) {
431 sb.append(" throws ");
432 for (int k = 0; k < exceptions.length; k++) {
433 sb.append((exceptions[k] instanceof Class)?
434 ((Class)exceptions[k]).getName():
435 exceptions[k].toString());
436 if (k < (exceptions.length - 1))
440 return sb.toString();
441 } catch (Exception e) {
442 return "<" + e + ">";
447 * Invokes the underlying method represented by this {@code Method}
448 * object, on the specified object with the specified parameters.
449 * Individual parameters are automatically unwrapped to match
450 * primitive formal parameters, and both primitive and reference
451 * parameters are subject to method invocation conversions as
454 * <p>If the underlying method is static, then the specified {@code obj}
455 * argument is ignored. It may be null.
457 * <p>If the number of formal parameters required by the underlying method is
458 * 0, the supplied {@code args} array may be of length 0 or null.
460 * <p>If the underlying method is an instance method, it is invoked
461 * using dynamic method lookup as documented in The Java Language
462 * Specification, Second Edition, section 15.12.4.4; in particular,
463 * overriding based on the runtime type of the target object will occur.
465 * <p>If the underlying method is static, the class that declared
466 * the method is initialized if it has not already been initialized.
468 * <p>If the method completes normally, the value it returns is
469 * returned to the caller of invoke; if the value has a primitive
470 * type, it is first appropriately wrapped in an object. However,
471 * if the value has the type of an array of a primitive type, the
472 * elements of the array are <i>not</i> wrapped in objects; in
473 * other words, an array of primitive type is returned. If the
474 * underlying method return type is void, the invocation returns
477 * @param obj the object the underlying method is invoked from
478 * @param args the arguments used for the method call
479 * @return the result of dispatching the method represented by
480 * this object on {@code obj} with parameters
483 * @exception IllegalAccessException if this {@code Method} object
484 * is enforcing Java language access control and the underlying
485 * method is inaccessible.
486 * @exception IllegalArgumentException if the method is an
487 * instance method and the specified object argument
488 * is not an instance of the class or interface
489 * declaring the underlying method (or of a subclass
490 * or implementor thereof); if the number of actual
491 * and formal parameters differ; if an unwrapping
492 * conversion for primitive arguments fails; or if,
493 * after possible unwrapping, a parameter value
494 * cannot be converted to the corresponding formal
495 * parameter type by a method invocation conversion.
496 * @exception InvocationTargetException if the underlying method
497 * throws an exception.
498 * @exception NullPointerException if the specified object is null
499 * and the method is an instance method.
500 * @exception ExceptionInInitializerError if the initialization
501 * provoked by this method fails.
503 public Object invoke(Object obj, Object... args)
504 throws IllegalAccessException, IllegalArgumentException,
505 InvocationTargetException
507 final boolean nonStatic = (getModifiers() & Modifier.STATIC) == 0;
508 if (nonStatic && obj == null) {
509 throw new NullPointerException();
511 Class[] types = getParameterTypes();
512 if (types.length != args.length) {
513 throw new IllegalArgumentException("Types len " + types.length + " args: " + args.length);
516 for (int i = 0; i < types.length; i++) {
518 if (c.isPrimitive() && args[i] != null) {
519 args[i] = toPrimitive(args[i]);
523 Object res = invokeTry(nonStatic, this, obj, args);
524 if (getReturnType().isPrimitive()) {
525 res = fromPrimitive(getReturnType(), res);
530 @JavaScriptBody(args = { "st", "method", "self", "args" }, body =
533 + " cll = self[method._name() + '__' + method._sig()];\n"
537 + " cll = method._data();"
539 + "return cll.apply(self, p);\n"
541 private static native Object invoke0(boolean isStatic, Method m, Object self, Object[] args);
543 private static Object invokeTry(boolean isStatic, Method m, Object self, Object[] args)
544 throws InvocationTargetException {
546 return invoke0(isStatic, m, self, args);
547 } catch (Throwable ex) {
548 throw new InvocationTargetException(ex, ex.getMessage());
552 static Object fromPrimitive(Class<?> type, Object o) {
553 if (samePrimitive(type, Integer.TYPE)) {
554 return fromRaw(Integer.class, "valueOf__Ljava_lang_Integer_2I", o);
556 if (samePrimitive(type, Long.TYPE)) {
557 return fromRaw(Long.class, "valueOf__Ljava_lang_Long_2J", o);
559 if (samePrimitive(type, Double.TYPE)) {
560 return fromRaw(Double.class, "valueOf__Ljava_lang_Double_2D", o);
562 if (samePrimitive(type, Float.TYPE)) {
563 return fromRaw(Float.class, "valueOf__Ljava_lang_Float_2F", o);
565 if (samePrimitive(type, Byte.TYPE)) {
566 return fromRaw(Byte.class, "valueOf__Ljava_lang_Byte_2B", o);
568 if (samePrimitive(type, Boolean.TYPE)) {
569 return fromRaw(Boolean.class, "valueOf__Ljava_lang_Boolean_2Z", o);
571 if (samePrimitive(type, Short.TYPE)) {
572 return fromRaw(Short.class, "valueOf__Ljava_lang_Short_2S", o);
574 if (samePrimitive(type, Character.TYPE)) {
575 return fromRaw(Character.class, "valueOf__Ljava_lang_Character_2C", o);
577 if (type.getName().equals("void")) {
580 throw new IllegalStateException("Can't convert " + o);
582 static boolean samePrimitive(Class<?> c1, Class<?> c2) {
586 if (c1.isPrimitive()) {
587 return c1.getName().equals(c2.getName());
592 static String findArraySignature(Class<?> type) {
593 if (!type.isPrimitive()) {
594 return "[L" + type.getName().replace('.', '/') + ";";
596 if (samePrimitive(type, Integer.TYPE)) {
599 if (samePrimitive(type, Long.TYPE)) {
602 if (samePrimitive(type, Double.TYPE)) {
605 if (samePrimitive(type, Float.TYPE)) {
608 if (samePrimitive(type, Byte.TYPE)) {
611 if (samePrimitive(type, Boolean.TYPE)) {
614 if (samePrimitive(type, Short.TYPE)) {
617 if (samePrimitive(type, Character.TYPE)) {
620 throw new IllegalStateException("Can't create array for " + type);
623 @JavaScriptBody(args = { "cls", "m", "o" },
624 body = "return cls.cnstr(false)[m](o);"
626 private static native Integer fromRaw(Class<?> cls, String m, Object o);
628 @JavaScriptBody(args = { "o" }, body = "return o.valueOf();")
629 static native Object toPrimitive(Object o);
632 * Returns {@code true} if this method is a bridge
633 * method; returns {@code false} otherwise.
635 * @return true if and only if this method is a bridge
636 * method as defined by the Java Language Specification.
639 public boolean isBridge() {
640 return (getModifiers() & Modifier.BRIDGE) != 0;
644 * Returns {@code true} if this method was declared to take
645 * a variable number of arguments; returns {@code false}
648 * @return {@code true} if an only if this method was declared to
649 * take a variable number of arguments.
652 public boolean isVarArgs() {
653 return (getModifiers() & Modifier.VARARGS) != 0;
657 * Returns {@code true} if this method is a synthetic
658 * method; returns {@code false} otherwise.
660 * @return true if and only if this method is a synthetic
661 * method as defined by the Java Language Specification.
664 public boolean isSynthetic() {
665 return Modifier.isSynthetic(getModifiers());
668 @JavaScriptBody(args = { "ac" },
670 "var a = this._data().anno;"
672 + " return a['L' + ac.jvmName + ';'];"
673 + "} else return null;"
675 private Object getAnnotationData(Class<?> annotationClass) {
676 throw new UnsupportedOperationException();
680 * @throws NullPointerException {@inheritDoc}
683 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
684 Object data = getAnnotationData(annotationClass);
685 return data == null ? null : AnnotationImpl.create(annotationClass, data);
691 public Annotation[] getDeclaredAnnotations() {
692 throw new UnsupportedOperationException();
696 * Returns the default value for the annotation member represented by
697 * this {@code Method} instance. If the member is of a primitive type,
698 * an instance of the corresponding wrapper type is returned. Returns
699 * null if no default is associated with the member, or if the method
700 * instance does not represent a declared member of an annotation type.
702 * @return the default value for the annotation member represented
703 * by this {@code Method} instance.
704 * @throws TypeNotPresentException if the annotation is of type
705 * {@link Class} and no definition can be found for the
706 * default class value.
709 public Object getDefaultValue() {
710 throw new UnsupportedOperationException();
714 * Returns an array of arrays that represent the annotations on the formal
715 * parameters, in declaration order, of the method represented by
716 * this {@code Method} object. (Returns an array of length zero if the
717 * underlying method is parameterless. If the method has one or more
718 * parameters, a nested array of length zero is returned for each parameter
719 * with no annotations.) The annotation objects contained in the returned
720 * arrays are serializable. The caller of this method is free to modify
721 * the returned arrays; it will have no effect on the arrays returned to
724 * @return an array of arrays that represent the annotations on the formal
725 * parameters, in declaration order, of the method represented by this
729 public Annotation[][] getParameterAnnotations() {
730 throw new UnsupportedOperationException();
734 MethodImpl.INSTANCE = new MethodImpl() {
735 protected Method create(Class<?> declaringClass, String name, Object data, String sig) {
736 return new Method(declaringClass, name, data, sig);
740 protected Constructor create(Class<?> declaringClass, Object data, String sig) {
741 return new Constructor(declaringClass, data, sig);
747 // helper methods for Array
750 @JavaScriptBody(args = { "primitive", "sig", "fn", "length" }, body =
751 "var arr = new Array(length);\n"
752 + "var value = primitive ? 0 : null;\n"
753 + "for(var i = 0; i < length; i++) arr[i] = value;\n"
754 + "Object.defineProperty(arr, 'jvmName', { 'configurable': true, 'writable': true, 'value': sig });\n"
755 + "Object.defineProperty(arr, 'fnc', { 'configurable': true, 'writable': true, 'value' : fn });\n"
756 // + "java.lang.System.out.println('Assigned ' + arr.jvmName + ' fn: ' + (!!arr.fnc));\n"
759 static native Object newArray(boolean primitive, String sig, Object fn, int length);
761 @JavaScriptBody(args = { "arr" }, body = "return arr.length;")
762 static native int arrayLength(Object arr);
764 @JavaScriptBody(args = { "cntstr" }, body = "return cntstr(false).constructor.$class;")
765 static native Class<?> classFromFn(Object cntstr);
766 @JavaScriptBody(args = { "array", "index" }, body = "return array[index];")
767 static native Object atArray(Object array, int index);
769 @JavaScriptBody(args = { "array", "index", "v" }, body = "array[index] = v;")
770 static native Object setArray(Object array, int index, Object v);