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() {
242 throw new UnsupportedOperationException();
243 //return (Class<?>[]) exceptionTypes.clone();
247 * Returns an array of {@code Type} objects that represent the
248 * exceptions declared to be thrown by this {@code Method} object.
249 * Returns an array of length 0 if the underlying method declares
250 * no exceptions in its {@code throws} clause.
252 * <p>If an exception type is a type variable or a parameterized
253 * type, it is created. Otherwise, it is resolved.
255 * @return an array of Types that represent the exception types
256 * thrown by the underlying method
257 * @throws GenericSignatureFormatError
258 * if the generic method signature does not conform to the format
260 * <cite>The Java™ Virtual Machine Specification</cite>
261 * @throws TypeNotPresentException if the underlying method's
262 * {@code throws} clause refers to a non-existent type declaration
263 * @throws MalformedParameterizedTypeException if
264 * the underlying method's {@code throws} clause refers to a
265 * parameterized type that cannot be instantiated for any reason
268 public Type[] getGenericExceptionTypes() {
269 throw new UnsupportedOperationException();
273 * Compares this {@code Method} against the specified object. Returns
274 * true if the objects are the same. Two {@code Methods} are the same if
275 * they were declared by the same class and have the same name
276 * and formal parameter types and return type.
278 public boolean equals(Object obj) {
279 if (obj != null && obj instanceof Method) {
280 Method other = (Method)obj;
281 return data == other.data;
287 * Returns a hashcode for this {@code Method}. The hashcode is computed
288 * as the exclusive-or of the hashcodes for the underlying
289 * method's declaring class name and the method's name.
291 public int hashCode() {
292 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
296 * Returns a string describing this {@code Method}. The string is
297 * formatted as the method access modifiers, if any, followed by
298 * the method return type, followed by a space, followed by the
299 * class declaring the method, followed by a period, followed by
300 * the method name, followed by a parenthesized, comma-separated
301 * list of the method's formal parameter types. If the method
302 * throws checked exceptions, the parameter list is followed by a
303 * space, followed by the word throws followed by a
304 * comma-separated list of the thrown exception types.
307 * public boolean java.lang.Object.equals(java.lang.Object)
310 * <p>The access modifiers are placed in canonical order as
311 * specified by "The Java Language Specification". This is
312 * {@code public}, {@code protected} or {@code private} first,
313 * and then other modifiers in the following order:
314 * {@code abstract}, {@code static}, {@code final},
315 * {@code synchronized}, {@code native}, {@code strictfp}.
317 public String toString() {
319 StringBuilder sb = new StringBuilder();
320 int mod = getModifiers() & Modifier.methodModifiers();
322 sb.append(Modifier.toString(mod)).append(' ');
324 sb.append(Field.getTypeName(getReturnType())).append(' ');
325 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
326 sb.append(getName()).append('(');
327 Class<?>[] params = getParameterTypes(); // avoid clone
328 for (int j = 0; j < params.length; j++) {
329 sb.append(Field.getTypeName(params[j]));
330 if (j < (params.length - 1))
335 Class<?>[] exceptions = exceptionTypes; // avoid clone
336 if (exceptions.length > 0) {
337 sb.append(" throws ");
338 for (int k = 0; k < exceptions.length; k++) {
339 sb.append(exceptions[k].getName());
340 if (k < (exceptions.length - 1))
345 return sb.toString();
346 } catch (Exception e) {
347 return "<" + e + ">";
352 * Returns a string describing this {@code Method}, including
353 * type parameters. The string is formatted as the method access
354 * modifiers, if any, followed by an angle-bracketed
355 * comma-separated list of the method's type parameters, if any,
356 * followed by the method's generic return type, followed by a
357 * space, followed by the class declaring the method, followed by
358 * a period, followed by the method name, followed by a
359 * parenthesized, comma-separated list of the method's generic
360 * formal parameter types.
362 * If this method was declared to take a variable number of
363 * arguments, instead of denoting the last parameter as
364 * "<tt><i>Type</i>[]</tt>", it is denoted as
365 * "<tt><i>Type</i>...</tt>".
367 * A space is used to separate access modifiers from one another
368 * and from the type parameters or return type. If there are no
369 * type parameters, the type parameter list is elided; if the type
370 * parameter list is present, a space separates the list from the
371 * class name. If the method is declared to throw exceptions, the
372 * parameter list is followed by a space, followed by the word
373 * throws followed by a comma-separated list of the generic thrown
374 * exception types. If there are no type parameters, the type
375 * parameter list is elided.
377 * <p>The access modifiers are placed in canonical order as
378 * specified by "The Java Language Specification". This is
379 * {@code public}, {@code protected} or {@code private} first,
380 * and then other modifiers in the following order:
381 * {@code abstract}, {@code static}, {@code final},
382 * {@code synchronized}, {@code native}, {@code strictfp}.
384 * @return a string describing this {@code Method},
385 * include type parameters
389 public String toGenericString() {
391 StringBuilder sb = new StringBuilder();
392 int mod = getModifiers() & Modifier.methodModifiers();
394 sb.append(Modifier.toString(mod)).append(' ');
396 TypeVariable<?>[] typeparms = getTypeParameters();
397 if (typeparms.length > 0) {
398 boolean first = true;
400 for(TypeVariable<?> typeparm: typeparms) {
403 // Class objects can't occur here; no need to test
404 // and call Class.getName().
405 sb.append(typeparm.toString());
411 Type genRetType = getGenericReturnType();
412 sb.append( ((genRetType instanceof Class<?>)?
413 Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
416 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
417 sb.append(getName()).append('(');
418 Type[] params = getGenericParameterTypes();
419 for (int j = 0; j < params.length; j++) {
420 String param = (params[j] instanceof Class)?
421 Field.getTypeName((Class)params[j]):
422 (params[j].toString());
423 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
424 param = param.replaceFirst("\\[\\]$", "...");
426 if (j < (params.length - 1))
430 Type[] exceptions = getGenericExceptionTypes();
431 if (exceptions.length > 0) {
432 sb.append(" throws ");
433 for (int k = 0; k < exceptions.length; k++) {
434 sb.append((exceptions[k] instanceof Class)?
435 ((Class)exceptions[k]).getName():
436 exceptions[k].toString());
437 if (k < (exceptions.length - 1))
441 return sb.toString();
442 } catch (Exception e) {
443 return "<" + e + ">";
448 * Invokes the underlying method represented by this {@code Method}
449 * object, on the specified object with the specified parameters.
450 * Individual parameters are automatically unwrapped to match
451 * primitive formal parameters, and both primitive and reference
452 * parameters are subject to method invocation conversions as
455 * <p>If the underlying method is static, then the specified {@code obj}
456 * argument is ignored. It may be null.
458 * <p>If the number of formal parameters required by the underlying method is
459 * 0, the supplied {@code args} array may be of length 0 or null.
461 * <p>If the underlying method is an instance method, it is invoked
462 * using dynamic method lookup as documented in The Java Language
463 * Specification, Second Edition, section 15.12.4.4; in particular,
464 * overriding based on the runtime type of the target object will occur.
466 * <p>If the underlying method is static, the class that declared
467 * the method is initialized if it has not already been initialized.
469 * <p>If the method completes normally, the value it returns is
470 * returned to the caller of invoke; if the value has a primitive
471 * type, it is first appropriately wrapped in an object. However,
472 * if the value has the type of an array of a primitive type, the
473 * elements of the array are <i>not</i> wrapped in objects; in
474 * other words, an array of primitive type is returned. If the
475 * underlying method return type is void, the invocation returns
478 * @param obj the object the underlying method is invoked from
479 * @param args the arguments used for the method call
480 * @return the result of dispatching the method represented by
481 * this object on {@code obj} with parameters
484 * @exception IllegalAccessException if this {@code Method} object
485 * is enforcing Java language access control and the underlying
486 * method is inaccessible.
487 * @exception IllegalArgumentException if the method is an
488 * instance method and the specified object argument
489 * is not an instance of the class or interface
490 * declaring the underlying method (or of a subclass
491 * or implementor thereof); if the number of actual
492 * and formal parameters differ; if an unwrapping
493 * conversion for primitive arguments fails; or if,
494 * after possible unwrapping, a parameter value
495 * cannot be converted to the corresponding formal
496 * parameter type by a method invocation conversion.
497 * @exception InvocationTargetException if the underlying method
498 * throws an exception.
499 * @exception NullPointerException if the specified object is null
500 * and the method is an instance method.
501 * @exception ExceptionInInitializerError if the initialization
502 * provoked by this method fails.
504 public Object invoke(Object obj, Object... args)
505 throws IllegalAccessException, IllegalArgumentException,
506 InvocationTargetException
508 final boolean nonStatic = (getModifiers() & Modifier.STATIC) == 0;
509 if (nonStatic && obj == null) {
510 throw new NullPointerException();
512 Class[] types = getParameterTypes();
513 if (types.length != args.length) {
514 throw new IllegalArgumentException("Types len " + types.length + " args: " + args.length);
517 for (int i = 0; i < types.length; i++) {
519 if (c.isPrimitive() && args[i] != null) {
520 args[i] = toPrimitive(args[i]);
524 Object res = invokeTry(nonStatic, this, obj, args);
525 if (getReturnType().isPrimitive()) {
526 res = fromPrimitive(getReturnType(), res);
531 @JavaScriptBody(args = { "st", "method", "self", "args" }, body =
534 + " p = new Array(1);\n"
536 + " p = p.concat(args);\n"
540 + "return method._data().apply(self, p);\n"
542 private static native Object invoke0(boolean isStatic, Method m, Object self, Object[] args);
544 private static Object invokeTry(boolean isStatic, Method m, Object self, Object[] args)
545 throws InvocationTargetException {
547 return invoke0(isStatic, m, self, args);
548 } catch (Throwable ex) {
549 throw new InvocationTargetException(ex, ex.getMessage());
553 static Object fromPrimitive(Class<?> type, Object o) {
554 if (type == Integer.TYPE) {
555 return fromRaw(Integer.class, "valueOf__Ljava_lang_Integer_2I", o);
557 if (type == Long.TYPE) {
558 return fromRaw(Long.class, "valueOf__Ljava_lang_Long_2J", o);
560 if (type == Double.TYPE) {
561 return fromRaw(Double.class, "valueOf__Ljava_lang_Double_2D", o);
563 if (type == Float.TYPE) {
564 return fromRaw(Float.class, "valueOf__Ljava_lang_Float_2F", o);
566 if (type == Byte.TYPE) {
567 return fromRaw(Byte.class, "valueOf__Ljava_lang_Byte_2B", o);
569 if (type == Boolean.TYPE) {
570 return fromRaw(Boolean.class, "valueOf__Ljava_lang_Boolean_2Z", o);
572 if (type == Short.TYPE) {
573 return fromRaw(Short.class, "valueOf__Ljava_lang_Short_2S", o);
575 if (type == Character.TYPE) {
576 return fromRaw(Character.class, "valueOf__Ljava_lang_Character_2C", o);
578 if (type.getName().equals("void")) {
581 throw new IllegalStateException("Can't convert " + o);
584 @JavaScriptBody(args = { "cls", "m", "o" },
585 body = "return cls.cnstr(false)[m](o);"
587 private static native Integer fromRaw(Class<?> cls, String m, Object o);
589 @JavaScriptBody(args = { "o" }, body = "return o.valueOf();")
590 static native Object toPrimitive(Object o);
593 * Returns {@code true} if this method is a bridge
594 * method; returns {@code false} otherwise.
596 * @return true if and only if this method is a bridge
597 * method as defined by the Java Language Specification.
600 public boolean isBridge() {
601 return (getModifiers() & Modifier.BRIDGE) != 0;
605 * Returns {@code true} if this method was declared to take
606 * a variable number of arguments; returns {@code false}
609 * @return {@code true} if an only if this method was declared to
610 * take a variable number of arguments.
613 public boolean isVarArgs() {
614 return (getModifiers() & Modifier.VARARGS) != 0;
618 * Returns {@code true} if this method is a synthetic
619 * method; returns {@code false} otherwise.
621 * @return true if and only if this method is a synthetic
622 * method as defined by the Java Language Specification.
625 public boolean isSynthetic() {
626 return Modifier.isSynthetic(getModifiers());
629 @JavaScriptBody(args = { "ac" },
631 "var a = this._data().anno;"
633 + " return a['L' + ac.jvmName + ';'];"
634 + "} else return null;"
636 private Object getAnnotationData(Class<?> annotationClass) {
637 throw new UnsupportedOperationException();
641 * @throws NullPointerException {@inheritDoc}
644 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
645 Object data = getAnnotationData(annotationClass);
646 return data == null ? null : AnnotationImpl.create(annotationClass, data);
652 public Annotation[] getDeclaredAnnotations() {
653 throw new UnsupportedOperationException();
657 * Returns the default value for the annotation member represented by
658 * this {@code Method} instance. If the member is of a primitive type,
659 * an instance of the corresponding wrapper type is returned. Returns
660 * null if no default is associated with the member, or if the method
661 * instance does not represent a declared member of an annotation type.
663 * @return the default value for the annotation member represented
664 * by this {@code Method} instance.
665 * @throws TypeNotPresentException if the annotation is of type
666 * {@link Class} and no definition can be found for the
667 * default class value.
670 public Object getDefaultValue() {
671 throw new UnsupportedOperationException();
675 * Returns an array of arrays that represent the annotations on the formal
676 * parameters, in declaration order, of the method represented by
677 * this {@code Method} object. (Returns an array of length zero if the
678 * underlying method is parameterless. If the method has one or more
679 * parameters, a nested array of length zero is returned for each parameter
680 * with no annotations.) The annotation objects contained in the returned
681 * arrays are serializable. The caller of this method is free to modify
682 * the returned arrays; it will have no effect on the arrays returned to
685 * @return an array of arrays that represent the annotations on the formal
686 * parameters, in declaration order, of the method represented by this
690 public Annotation[][] getParameterAnnotations() {
691 throw new UnsupportedOperationException();
695 MethodImpl.INSTANCE = new MethodImpl() {
696 protected Method create(Class<?> declaringClass, String name, Object data, String sig) {
697 return new Method(declaringClass, name, data, sig);
701 protected Constructor create(Class<?> declaringClass, Object data, String sig) {
702 return new Constructor(declaringClass, data, sig);