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;
31 import org.apidesign.bck2brwsr.emul.MethodImpl;
34 * A {@code Method} provides information about, and access to, a single method
35 * on a class or interface. The reflected method may be a class method
36 * or an instance method (including an abstract method).
38 * <p>A {@code Method} permits widening conversions to occur when matching the
39 * actual parameters to invoke with the underlying method's formal
40 * parameters, but it throws an {@code IllegalArgumentException} if a
41 * narrowing conversion would occur.
44 * @see java.lang.Class
45 * @see java.lang.Class#getMethods()
46 * @see java.lang.Class#getMethod(String, Class[])
47 * @see java.lang.Class#getDeclaredMethods()
48 * @see java.lang.Class#getDeclaredMethod(String, Class[])
50 * @author Kenneth Russell
51 * @author Nakul Saraiya
54 class Method extends AccessibleObject implements GenericDeclaration,
56 private final Class<?> clazz;
57 private final String name;
58 private final Object data;
59 private final String sig;
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() {
111 return getAccess(data);
114 @JavaScriptBody(args = "self", body = "return self.access;")
115 private static native int getAccess(Object self);
118 * Returns an array of {@code TypeVariable} objects that represent the
119 * type variables declared by the generic declaration represented by this
120 * {@code GenericDeclaration} object, in declaration order. Returns an
121 * array of length 0 if the underlying generic declaration declares no type
124 * @return an array of {@code TypeVariable} objects that represent
125 * the type variables declared by this generic declaration
126 * @throws GenericSignatureFormatError if the generic
127 * signature of this generic declaration does not conform to
128 * the format specified in
129 * <cite>The Java™ Virtual Machine Specification</cite>
132 public TypeVariable<Method>[] getTypeParameters() {
133 throw new UnsupportedOperationException();
137 * Returns a {@code Class} object that represents the formal return type
138 * of the method represented by this {@code Method} object.
140 * @return the return type for the method this object represents
142 public Class<?> getReturnType() {
143 switch (sig.charAt(0)) {
144 case 'I': return Integer.TYPE;
145 case 'J': return Long.TYPE;
146 case 'D': return Double.TYPE;
147 case 'F': return Float.TYPE;
148 case 'B': return Byte.TYPE;
149 case 'Z': return Boolean.TYPE;
150 case 'S': return Short.TYPE;
151 case 's': return String.class;
152 // case 'V': return Void.TYPE;
154 int up = sig.indexOf("_2");
155 String type = sig.substring(1, up);
156 return Class.forName(type);
157 } catch (ClassNotFoundException ex) {
161 throw new UnsupportedOperationException(sig);
165 * Returns a {@code Type} object that represents the formal return
166 * type of the method represented by this {@code Method} object.
168 * <p>If the return type is a parameterized type,
169 * the {@code Type} object returned must accurately reflect
170 * the actual type parameters used in the source code.
172 * <p>If the return type is a type variable or a parameterized type, it
173 * is created. Otherwise, it is resolved.
175 * @return a {@code Type} object that represents the formal return
176 * type of the underlying method
177 * @throws GenericSignatureFormatError
178 * if the generic method signature does not conform to the format
180 * <cite>The Java™ Virtual Machine Specification</cite>
181 * @throws TypeNotPresentException if the underlying method's
182 * return type refers to a non-existent type declaration
183 * @throws MalformedParameterizedTypeException if the
184 * underlying method's return typed refers to a parameterized
185 * type that cannot be instantiated for any reason
188 public Type getGenericReturnType() {
189 throw new UnsupportedOperationException();
194 * Returns an array of {@code Class} objects that represent the formal
195 * parameter types, in declaration order, of the method
196 * represented by this {@code Method} object. Returns an array of length
197 * 0 if the underlying method takes no parameters.
199 * @return the parameter types for the method this object
202 public Class<?>[] getParameterTypes() {
203 throw new UnsupportedOperationException();
204 //return (Class<?>[]) parameterTypes.clone();
208 * Returns an array of {@code Type} objects that represent the formal
209 * parameter types, in declaration order, of the method represented by
210 * this {@code Method} object. Returns an array of length 0 if the
211 * underlying method takes no parameters.
213 * <p>If a formal parameter type is a parameterized type,
214 * the {@code Type} object returned for it must accurately reflect
215 * the actual type parameters used in the source code.
217 * <p>If a formal parameter type is a type variable or a parameterized
218 * type, it is created. Otherwise, it is resolved.
220 * @return an array of Types that represent the formal
221 * parameter types of the underlying method, in declaration order
222 * @throws GenericSignatureFormatError
223 * if the generic method signature does not conform to the format
225 * <cite>The Java™ Virtual Machine Specification</cite>
226 * @throws TypeNotPresentException if any of the parameter
227 * types of the underlying method refers to a non-existent type
229 * @throws MalformedParameterizedTypeException if any of
230 * the underlying method's parameter types refer to a parameterized
231 * type that cannot be instantiated for any reason
234 public Type[] getGenericParameterTypes() {
235 throw new UnsupportedOperationException();
240 * Returns an array of {@code Class} objects that represent
241 * the types of the exceptions declared to be thrown
242 * by the underlying method
243 * represented by this {@code Method} object. Returns an array of length
244 * 0 if the method declares no exceptions in its {@code throws} clause.
246 * @return the exception types declared as being thrown by the
247 * method this object represents
249 public Class<?>[] getExceptionTypes() {
250 throw new UnsupportedOperationException();
251 //return (Class<?>[]) exceptionTypes.clone();
255 * Returns an array of {@code Type} objects that represent the
256 * exceptions declared to be thrown by this {@code Method} object.
257 * Returns an array of length 0 if the underlying method declares
258 * no exceptions in its {@code throws} clause.
260 * <p>If an exception type is a type variable or a parameterized
261 * type, it is created. Otherwise, it is resolved.
263 * @return an array of Types that represent the exception types
264 * thrown by the underlying method
265 * @throws GenericSignatureFormatError
266 * if the generic method signature does not conform to the format
268 * <cite>The Java™ Virtual Machine Specification</cite>
269 * @throws TypeNotPresentException if the underlying method's
270 * {@code throws} clause refers to a non-existent type declaration
271 * @throws MalformedParameterizedTypeException if
272 * the underlying method's {@code throws} clause refers to a
273 * parameterized type that cannot be instantiated for any reason
276 public Type[] getGenericExceptionTypes() {
277 throw new UnsupportedOperationException();
281 * Compares this {@code Method} against the specified object. Returns
282 * true if the objects are the same. Two {@code Methods} are the same if
283 * they were declared by the same class and have the same name
284 * and formal parameter types and return type.
286 public boolean equals(Object obj) {
287 if (obj != null && obj instanceof Method) {
288 Method other = (Method)obj;
289 return data == other.data;
295 * Returns a hashcode for this {@code Method}. The hashcode is computed
296 * as the exclusive-or of the hashcodes for the underlying
297 * method's declaring class name and the method's name.
299 public int hashCode() {
300 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
304 * Returns a string describing this {@code Method}. The string is
305 * formatted as the method access modifiers, if any, followed by
306 * the method return type, followed by a space, followed by the
307 * class declaring the method, followed by a period, followed by
308 * the method name, followed by a parenthesized, comma-separated
309 * list of the method's formal parameter types. If the method
310 * throws checked exceptions, the parameter list is followed by a
311 * space, followed by the word throws followed by a
312 * comma-separated list of the thrown exception types.
315 * public boolean java.lang.Object.equals(java.lang.Object)
318 * <p>The access modifiers are placed in canonical order as
319 * specified by "The Java Language Specification". This is
320 * {@code public}, {@code protected} or {@code private} first,
321 * and then other modifiers in the following order:
322 * {@code abstract}, {@code static}, {@code final},
323 * {@code synchronized}, {@code native}, {@code strictfp}.
325 public String toString() {
327 StringBuilder sb = new StringBuilder();
328 int mod = getModifiers() & Modifier.methodModifiers();
330 sb.append(Modifier.toString(mod)).append(' ');
332 sb.append(Field.getTypeName(getReturnType())).append(' ');
333 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
334 sb.append(getName()).append('(');
336 Class<?>[] params = parameterTypes; // avoid clone
337 for (int j = 0; j < params.length; j++) {
338 sb.append(Field.getTypeName(params[j]));
339 if (j < (params.length - 1))
343 Class<?>[] exceptions = exceptionTypes; // avoid clone
344 if (exceptions.length > 0) {
345 sb.append(" throws ");
346 for (int k = 0; k < exceptions.length; k++) {
347 sb.append(exceptions[k].getName());
348 if (k < (exceptions.length - 1))
353 return sb.toString();
354 } catch (Exception e) {
355 return "<" + e + ">";
360 * Returns a string describing this {@code Method}, including
361 * type parameters. The string is formatted as the method access
362 * modifiers, if any, followed by an angle-bracketed
363 * comma-separated list of the method's type parameters, if any,
364 * followed by the method's generic return type, followed by a
365 * space, followed by the class declaring the method, followed by
366 * a period, followed by the method name, followed by a
367 * parenthesized, comma-separated list of the method's generic
368 * formal parameter types.
370 * If this method was declared to take a variable number of
371 * arguments, instead of denoting the last parameter as
372 * "<tt><i>Type</i>[]</tt>", it is denoted as
373 * "<tt><i>Type</i>...</tt>".
375 * A space is used to separate access modifiers from one another
376 * and from the type parameters or return type. If there are no
377 * type parameters, the type parameter list is elided; if the type
378 * parameter list is present, a space separates the list from the
379 * class name. If the method is declared to throw exceptions, the
380 * parameter list is followed by a space, followed by the word
381 * throws followed by a comma-separated list of the generic thrown
382 * exception types. If there are no type parameters, the type
383 * parameter list is elided.
385 * <p>The access modifiers are placed in canonical order as
386 * specified by "The Java Language Specification". This is
387 * {@code public}, {@code protected} or {@code private} first,
388 * and then other modifiers in the following order:
389 * {@code abstract}, {@code static}, {@code final},
390 * {@code synchronized}, {@code native}, {@code strictfp}.
392 * @return a string describing this {@code Method},
393 * include type parameters
397 public String toGenericString() {
399 StringBuilder sb = new StringBuilder();
400 int mod = getModifiers() & Modifier.methodModifiers();
402 sb.append(Modifier.toString(mod)).append(' ');
404 TypeVariable<?>[] typeparms = getTypeParameters();
405 if (typeparms.length > 0) {
406 boolean first = true;
408 for(TypeVariable<?> typeparm: typeparms) {
411 // Class objects can't occur here; no need to test
412 // and call Class.getName().
413 sb.append(typeparm.toString());
419 Type genRetType = getGenericReturnType();
420 sb.append( ((genRetType instanceof Class<?>)?
421 Field.getTypeName((Class<?>)genRetType):genRetType.toString()))
424 sb.append(Field.getTypeName(getDeclaringClass())).append('.');
425 sb.append(getName()).append('(');
426 Type[] params = getGenericParameterTypes();
427 for (int j = 0; j < params.length; j++) {
428 String param = (params[j] instanceof Class)?
429 Field.getTypeName((Class)params[j]):
430 (params[j].toString());
431 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
432 param = param.replaceFirst("\\[\\]$", "...");
434 if (j < (params.length - 1))
438 Type[] exceptions = getGenericExceptionTypes();
439 if (exceptions.length > 0) {
440 sb.append(" throws ");
441 for (int k = 0; k < exceptions.length; k++) {
442 sb.append((exceptions[k] instanceof Class)?
443 ((Class)exceptions[k]).getName():
444 exceptions[k].toString());
445 if (k < (exceptions.length - 1))
449 return sb.toString();
450 } catch (Exception e) {
451 return "<" + e + ">";
456 * Invokes the underlying method represented by this {@code Method}
457 * object, on the specified object with the specified parameters.
458 * Individual parameters are automatically unwrapped to match
459 * primitive formal parameters, and both primitive and reference
460 * parameters are subject to method invocation conversions as
463 * <p>If the underlying method is static, then the specified {@code obj}
464 * argument is ignored. It may be null.
466 * <p>If the number of formal parameters required by the underlying method is
467 * 0, the supplied {@code args} array may be of length 0 or null.
469 * <p>If the underlying method is an instance method, it is invoked
470 * using dynamic method lookup as documented in The Java Language
471 * Specification, Second Edition, section 15.12.4.4; in particular,
472 * overriding based on the runtime type of the target object will occur.
474 * <p>If the underlying method is static, the class that declared
475 * the method is initialized if it has not already been initialized.
477 * <p>If the method completes normally, the value it returns is
478 * returned to the caller of invoke; if the value has a primitive
479 * type, it is first appropriately wrapped in an object. However,
480 * if the value has the type of an array of a primitive type, the
481 * elements of the array are <i>not</i> wrapped in objects; in
482 * other words, an array of primitive type is returned. If the
483 * underlying method return type is void, the invocation returns
486 * @param obj the object the underlying method is invoked from
487 * @param args the arguments used for the method call
488 * @return the result of dispatching the method represented by
489 * this object on {@code obj} with parameters
492 * @exception IllegalAccessException if this {@code Method} object
493 * is enforcing Java language access control and the underlying
494 * method is inaccessible.
495 * @exception IllegalArgumentException if the method is an
496 * instance method and the specified object argument
497 * is not an instance of the class or interface
498 * declaring the underlying method (or of a subclass
499 * or implementor thereof); if the number of actual
500 * and formal parameters differ; if an unwrapping
501 * conversion for primitive arguments fails; or if,
502 * after possible unwrapping, a parameter value
503 * cannot be converted to the corresponding formal
504 * parameter type by a method invocation conversion.
505 * @exception InvocationTargetException if the underlying method
506 * throws an exception.
507 * @exception NullPointerException if the specified object is null
508 * and the method is an instance method.
509 * @exception ExceptionInInitializerError if the initialization
510 * provoked by this method fails.
512 public Object invoke(Object obj, Object... args)
513 throws IllegalAccessException, IllegalArgumentException,
514 InvocationTargetException
516 Object res = invoke0(this, obj, args);
517 if (getReturnType().isPrimitive()) {
518 res = fromPrimitive(getReturnType(), res);
523 @JavaScriptBody(args = { "method", "self", "args" }, body =
524 "if (args.length > 0) throw 'unsupported now';"
525 + "return method.fld_data(self);"
527 private static native Object invoke0(Method m, Object self, Object[] args);
529 private static Object fromPrimitive(Class<?> type, Object o) {
530 if (type == Integer.TYPE) {
531 return fromRaw(Integer.class, "valueOf__Ljava_lang_Integer_2I", o);
533 if (type == Long.TYPE) {
534 return fromRaw(Long.class, "valueOf__Ljava_lang_Long_2J", o);
536 if (type == Double.TYPE) {
537 return fromRaw(Double.class, "valueOf__Ljava_lang_Double_2D", o);
539 if (type == Float.TYPE) {
540 return fromRaw(Float.class, "valueOf__Ljava_lang_Float_2F", o);
542 if (type == Byte.TYPE) {
543 return fromRaw(Byte.class, "valueOf__Ljava_lang_Byte_2B", o);
545 if (type == Boolean.TYPE) {
546 return fromRaw(Boolean.class, "valueOf__Ljava_lang_Boolean_2Z", o);
548 if (type == Short.TYPE) {
549 return fromRaw(Short.class, "valueOf__Ljava_lang_Short_2S", o);
551 // case 'V': return Void.TYPE;
552 throw new IllegalStateException("Can't convert " + o);
555 @JavaScriptBody(args = { "cls", "m", "o" },
556 body = "return cls.cnstr(false)[m](o);"
558 private static native Integer fromRaw(Class<?> cls, String m, Object o);
561 * Returns {@code true} if this method is a bridge
562 * method; returns {@code false} otherwise.
564 * @return true if and only if this method is a bridge
565 * method as defined by the Java Language Specification.
568 public boolean isBridge() {
569 return (getModifiers() & Modifier.BRIDGE) != 0;
573 * Returns {@code true} if this method was declared to take
574 * a variable number of arguments; returns {@code false}
577 * @return {@code true} if an only if this method was declared to
578 * take a variable number of arguments.
581 public boolean isVarArgs() {
582 return (getModifiers() & Modifier.VARARGS) != 0;
586 * Returns {@code true} if this method is a synthetic
587 * method; returns {@code false} otherwise.
589 * @return true if and only if this method is a synthetic
590 * method as defined by the Java Language Specification.
593 public boolean isSynthetic() {
594 return Modifier.isSynthetic(getModifiers());
597 @JavaScriptBody(args = { "self", "ac" },
599 "if (self.fld_data.anno) {"
600 + " return self.fld_data.anno['L' + ac.jvmName + ';'];"
601 + "} else return null;"
603 private Object getAnnotationData(Class<?> annotationClass) {
604 throw new UnsupportedOperationException();
608 * @throws NullPointerException {@inheritDoc}
611 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
612 Object data = getAnnotationData(annotationClass);
613 return data == null ? null : AnnotationImpl.create(annotationClass, data);
619 public Annotation[] getDeclaredAnnotations() {
620 throw new UnsupportedOperationException();
624 * Returns the default value for the annotation member represented by
625 * this {@code Method} instance. If the member is of a primitive type,
626 * an instance of the corresponding wrapper type is returned. Returns
627 * null if no default is associated with the member, or if the method
628 * instance does not represent a declared member of an annotation type.
630 * @return the default value for the annotation member represented
631 * by this {@code Method} instance.
632 * @throws TypeNotPresentException if the annotation is of type
633 * {@link Class} and no definition can be found for the
634 * default class value.
637 public Object getDefaultValue() {
638 throw new UnsupportedOperationException();
642 * Returns an array of arrays that represent the annotations on the formal
643 * parameters, in declaration order, of the method represented by
644 * this {@code Method} object. (Returns an array of length zero if the
645 * underlying method is parameterless. If the method has one or more
646 * parameters, a nested array of length zero is returned for each parameter
647 * with no annotations.) The annotation objects contained in the returned
648 * arrays are serializable. The caller of this method is free to modify
649 * the returned arrays; it will have no effect on the arrays returned to
652 * @return an array of arrays that represent the annotations on the formal
653 * parameters, in declaration order, of the method represented by this
657 public Annotation[][] getParameterAnnotations() {
658 throw new UnsupportedOperationException();
662 MethodImpl.INSTANCE = new MethodImpl() {
663 protected Method create(Class<?> declaringClass, String name, Object data, String sig) {
664 return new Method(declaringClass, name, data, sig);