1 /*
2 * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
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.
10 *
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).
16 *
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.
20 *
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
23 * questions.
24 */
25
26 package java.lang.reflect;
27
28 import jdk.internal.HotSpotIntrinsicCandidate;
29 import jdk.internal.misc.SharedSecrets;
30 import jdk.internal.reflect.CallerSensitive;
31 import jdk.internal.reflect.MethodAccessor;
32 import jdk.internal.reflect.Reflection;
33 import jdk.internal.vm.annotation.ForceInline;
34 import sun.reflect.annotation.ExceptionProxy;
35 import sun.reflect.annotation.TypeNotPresentExceptionProxy;
36 import sun.reflect.generics.repository.MethodRepository;
37 import sun.reflect.generics.factory.CoreReflectionFactory;
38 import sun.reflect.generics.factory.GenericsFactory;
39 import sun.reflect.generics.scope.MethodScope;
40 import sun.reflect.annotation.AnnotationType;
41 import sun.reflect.annotation.AnnotationParser;
42 import java.lang.annotation.Annotation;
43 import java.lang.annotation.AnnotationFormatError;
44 import java.nio.ByteBuffer;
45 import java.util.StringJoiner;
46
47 /**
48 * A {@code Method} provides information about, and access to, a single method
49 * on a class or interface. The reflected method may be a class method
50 * or an instance method (including an abstract method).
51 *
52 * <p>A {@code Method} permits widening conversions to occur when matching the
53 * actual parameters to invoke with the underlying method's formal
54 * parameters, but it throws an {@code IllegalArgumentException} if a
55 * narrowing conversion would occur.
56 *
57 * @see Member
58 * @see java.lang.Class
59 * @see java.lang.Class#getMethods()
60 * @see java.lang.Class#getMethod(String, Class[])
61 * @see java.lang.Class#getDeclaredMethods()
62 * @see java.lang.Class#getDeclaredMethod(String, Class[])
63 *
64 * @author Kenneth Russell
65 * @author Nakul Saraiya
66 * @since 1.1
67 */
68 public final class Method extends Executable {
69 private Class<?> clazz;
70 private int slot;
71 // This is guaranteed to be interned by the VM in the 1.4
72 // reflection implementation
73 private String name;
74 private Class<?> returnType;
75 private Class<?>[] parameterTypes;
76 private Class<?>[] exceptionTypes;
77 private int modifiers;
78 // Generics and annotations support
79 private transient String signature;
80 // generic info repository; lazily initialized
81 private transient MethodRepository genericInfo;
82 private byte[] annotations;
83 private byte[] parameterAnnotations;
84 private byte[] annotationDefault;
85 private volatile MethodAccessor methodAccessor;
86 // For sharing of MethodAccessors. This branching structure is
87 // currently only two levels deep (i.e., one root Method and
88 // potentially many Method objects pointing to it.)
89 //
90 // If this branching structure would ever contain cycles, deadlocks can
91 // occur in annotation code.
92 private Method root;
93
94 // Generics infrastructure
95 private String getGenericSignature() {return signature;}
96
97 // Accessor for factory
98 private GenericsFactory getFactory() {
99 // create scope and factory
100 return CoreReflectionFactory.make(this, MethodScope.make(this));
101 }
102
103 // Accessor for generic info repository
104 @Override
105 MethodRepository getGenericInfo() {
106 // lazily initialize repository if necessary
107 if (genericInfo == null) {
108 // create and cache generic info repository
109 genericInfo = MethodRepository.make(getGenericSignature(),
110 getFactory());
111 }
112 return genericInfo; //return cached repository
113 }
114
115 /**
116 * Package-private constructor used by ReflectAccess to enable
117 * instantiation of these objects in Java code from the java.lang
118 * package via sun.reflect.LangReflectAccess.
119 */
120 Method(Class<?> declaringClass,
121 String name,
122 Class<?>[] parameterTypes,
123 Class<?> returnType,
124 Class<?>[] checkedExceptions,
125 int modifiers,
126 int slot,
127 String signature,
128 byte[] annotations,
129 byte[] parameterAnnotations,
130 byte[] annotationDefault) {
131 this.clazz = declaringClass;
132 this.name = name;
133 this.parameterTypes = parameterTypes;
134 this.returnType = returnType;
135 this.exceptionTypes = checkedExceptions;
136 this.modifiers = modifiers;
137 this.slot = slot;
138 this.signature = signature;
139 this.annotations = annotations;
140 this.parameterAnnotations = parameterAnnotations;
141 this.annotationDefault = annotationDefault;
142 }
143
144 /**
145 * Package-private routine (exposed to java.lang.Class via
146 * ReflectAccess) which returns a copy of this Method. The copy's
147 * "root" field points to this Method.
148 */
149 Method copy() {
150 // This routine enables sharing of MethodAccessor objects
151 // among Method objects which refer to the same underlying
152 // method in the VM. (All of this contortion is only necessary
153 // because of the "accessibility" bit in AccessibleObject,
154 // which implicitly requires that new java.lang.reflect
155 // objects be fabricated for each reflective call on Class
156 // objects.)
157 if (this.root != null)
158 throw new IllegalArgumentException("Can not copy a non-root Method");
159
160 Method res = new Method(clazz, name, parameterTypes, returnType,
161 exceptionTypes, modifiers, slot, signature,
162 annotations, parameterAnnotations, annotationDefault);
163 res.root = this;
164 // Might as well eagerly propagate this if already present
165 res.methodAccessor = methodAccessor;
166 return res;
167 }
168
169 /**
170 * Make a copy of a leaf method.
171 */
172 Method leafCopy() {
173 if (this.root == null)
174 throw new IllegalArgumentException("Can only leafCopy a non-root Method");
175
176 Method res = new Method(clazz, name, parameterTypes, returnType,
177 exceptionTypes, modifiers, slot, signature,
178 annotations, parameterAnnotations, annotationDefault);
179 res.root = root;
180 res.methodAccessor = methodAccessor;
181 return res;
182 }
183
184 /**
185 * @throws InaccessibleObjectException {@inheritDoc}
186 * @throws SecurityException {@inheritDoc}
187 */
188 @Override
189 @CallerSensitive
190 public void setAccessible(boolean flag) {
191 AccessibleObject.checkPermission();
192 if (flag) checkCanSetAccessible(Reflection.getCallerClass());
193 setAccessible0(flag);
194 }
195
196 @Override
197 void checkCanSetAccessible(Class<?> caller) {
198 checkCanSetAccessible(caller, clazz);
199 }
200
201 @Override
202 Method getRoot() {
203 return root;
204 }
205
206 @Override
207 boolean hasGenericInformation() {
208 return (getGenericSignature() != null);
209 }
210
211 @Override
212 byte[] getAnnotationBytes() {
213 return annotations;
214 }
215
216 /**
217 * Returns the {@code Class} object representing the class or interface
218 * that declares the method represented by this object.
219 */
220 @Override
221 public Class<?> getDeclaringClass() {
222 return clazz;
223 }
224
225 /**
226 * Returns the name of the method represented by this {@code Method}
227 * object, as a {@code String}.
228 */
229 @Override
230 public String getName() {
231 return name;
232 }
233
234 /**
235 * {@inheritDoc}
236 */
237 @Override
238 public int getModifiers() {
239 return modifiers;
240 }
241
242 /**
243 * {@inheritDoc}
244 * @throws GenericSignatureFormatError {@inheritDoc}
245 * @since 1.5
246 */
247 @Override
248 @SuppressWarnings({"rawtypes", "unchecked"})
249 public TypeVariable<Method>[] getTypeParameters() {
250 if (getGenericSignature() != null)
251 return (TypeVariable<Method>[])getGenericInfo().getTypeParameters();
252 else
253 return (TypeVariable<Method>[])new TypeVariable[0];
254 }
255
256 /**
257 * Returns a {@code Class} object that represents the formal return type
258 * of the method represented by this {@code Method} object.
259 *
260 * @return the return type for the method this object represents
261 */
262 public Class<?> getReturnType() {
263 return returnType;
264 }
265
266 /**
267 * Returns a {@code Type} object that represents the formal return
268 * type of the method represented by this {@code Method} object.
269 *
270 * <p>If the return type is a parameterized type,
271 * the {@code Type} object returned must accurately reflect
272 * the actual type parameters used in the source code.
273 *
274 * <p>If the return type is a type variable or a parameterized type, it
275 * is created. Otherwise, it is resolved.
276 *
277 * @return a {@code Type} object that represents the formal return
278 * type of the underlying method
279 * @throws GenericSignatureFormatError
280 * if the generic method signature does not conform to the format
281 * specified in
282 * <cite>The Java™ Virtual Machine Specification</cite>
283 * @throws TypeNotPresentException if the underlying method's
284 * return type refers to a non-existent type declaration
285 * @throws MalformedParameterizedTypeException if the
286 * underlying method's return typed refers to a parameterized
287 * type that cannot be instantiated for any reason
288 * @since 1.5
289 */
290 public Type getGenericReturnType() {
291 if (getGenericSignature() != null) {
292 return getGenericInfo().getReturnType();
293 } else { return getReturnType();}
294 }
295
296 @Override
297 Class<?>[] getSharedParameterTypes() {
298 return parameterTypes;
299 }
300
301 @Override
302 Class<?>[] getSharedExceptionTypes() {
303 return exceptionTypes;
304 }
305
306 /**
307 * {@inheritDoc}
308 */
309 @Override
310 public Class<?>[] getParameterTypes() {
311 return parameterTypes.clone();
312 }
313
314 /**
315 * {@inheritDoc}
316 * @since 1.8
317 */
318 public int getParameterCount() { return parameterTypes.length; }
319
320
321 /**
322 * {@inheritDoc}
323 * @throws GenericSignatureFormatError {@inheritDoc}
324 * @throws TypeNotPresentException {@inheritDoc}
325 * @throws MalformedParameterizedTypeException {@inheritDoc}
326 * @since 1.5
327 */
328 @Override
329 public Type[] getGenericParameterTypes() {
330 return super.getGenericParameterTypes();
331 }
332
333 /**
334 * {@inheritDoc}
335 */
336 @Override
337 public Class<?>[] getExceptionTypes() {
338 return exceptionTypes.clone();
339 }
340
341 /**
342 * {@inheritDoc}
343 * @throws GenericSignatureFormatError {@inheritDoc}
344 * @throws TypeNotPresentException {@inheritDoc}
345 * @throws MalformedParameterizedTypeException {@inheritDoc}
346 * @since 1.5
347 */
348 @Override
349 public Type[] getGenericExceptionTypes() {
350 return super.getGenericExceptionTypes();
351 }
352
353 /**
354 * Compares this {@code Method} against the specified object. Returns
355 * true if the objects are the same. Two {@code Methods} are the same if
356 * they were declared by the same class and have the same name
357 * and formal parameter types and return type.
358 */
359 public boolean equals(Object obj) {
360 if (obj != null && obj instanceof Method) {
361 Method other = (Method)obj;
362 if ((getDeclaringClass() == other.getDeclaringClass())
363 && (getName() == other.getName())) {
364 if (!returnType.equals(other.getReturnType()))
365 return false;
366 return equalParamTypes(parameterTypes, other.parameterTypes);
367 }
368 }
369 return false;
370 }
371
372 /**
373 * Returns a hashcode for this {@code Method}. The hashcode is computed
374 * as the exclusive-or of the hashcodes for the underlying
375 * method's declaring class name and the method's name.
376 */
377 public int hashCode() {
378 return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
379 }
380
381 /**
382 * Returns a string describing this {@code Method}. The string is
383 * formatted as the method access modifiers, if any, followed by
384 * the method return type, followed by a space, followed by the
385 * class declaring the method, followed by a period, followed by
386 * the method name, followed by a parenthesized, comma-separated
387 * list of the method's formal parameter types. If the method
388 * throws checked exceptions, the parameter list is followed by a
389 * space, followed by the word "{@code throws}" followed by a
390 * comma-separated list of the thrown exception types.
391 * For example:
392 * <pre>
393 * public boolean java.lang.Object.equals(java.lang.Object)
394 * </pre>
395 *
396 * <p>The access modifiers are placed in canonical order as
397 * specified by "The Java Language Specification". This is
398 * {@code public}, {@code protected} or {@code private} first,
399 * and then other modifiers in the following order:
400 * {@code abstract}, {@code default}, {@code static}, {@code final},
401 * {@code synchronized}, {@code native}, {@code strictfp}.
402 *
403 * @return a string describing this {@code Method}
404 *
405 * @jls 8.4.3 Method Modifiers
406 * @jls 9.4 Method Declarations
407 * @jls 9.6.1 Annotation Type Elements
408 */
409 public String toString() {
410 return sharedToString(Modifier.methodModifiers(),
411 isDefault(),
412 parameterTypes,
413 exceptionTypes);
414 }
415
416 @Override
417 void specificToStringHeader(StringBuilder sb) {
418 sb.append(getReturnType().getTypeName()).append(' ');
419 sb.append(getDeclaringClass().getTypeName()).append('.');
420 sb.append(getName());
421 }
422
423 @Override
424 String toShortString() {
425 StringBuilder sb = new StringBuilder("method ");
426 sb.append(getDeclaringClass().getTypeName()).append('.');
427 sb.append(getName());
428 sb.append('(');
429 StringJoiner sj = new StringJoiner(",");
430 for (Class<?> parameterType : getParameterTypes()) {
431 sj.add(parameterType.getTypeName());
432 }
433 sb.append(sj);
434 sb.append(')');
435 return sb.toString();
436 }
437
438 /**
439 * Returns a string describing this {@code Method}, including
440 * type parameters. The string is formatted as the method access
441 * modifiers, if any, followed by an angle-bracketed
442 * comma-separated list of the method's type parameters, if any,
443 * followed by the method's generic return type, followed by a
444 * space, followed by the class declaring the method, followed by
445 * a period, followed by the method name, followed by a
446 * parenthesized, comma-separated list of the method's generic
447 * formal parameter types.
448 *
449 * If this method was declared to take a variable number of
450 * arguments, instead of denoting the last parameter as
451 * "<code><i>Type</i>[]</code>", it is denoted as
452 * "<code><i>Type</i>...</code>".
453 *
454 * A space is used to separate access modifiers from one another
455 * and from the type parameters or return type. If there are no
456 * type parameters, the type parameter list is elided; if the type
457 * parameter list is present, a space separates the list from the
458 * class name. If the method is declared to throw exceptions, the
459 * parameter list is followed by a space, followed by the word
460 * "{@code throws}" followed by a comma-separated list of the generic
461 * thrown exception types.
462 *
463 * <p>The access modifiers are placed in canonical order as
464 * specified by "The Java Language Specification". This is
465 * {@code public}, {@code protected} or {@code private} first,
466 * and then other modifiers in the following order:
467 * {@code abstract}, {@code default}, {@code static}, {@code final},
468 * {@code synchronized}, {@code native}, {@code strictfp}.
469 *
470 * @return a string describing this {@code Method},
471 * include type parameters
472 *
473 * @since 1.5
474 *
475 * @jls 8.4.3 Method Modifiers
476 * @jls 9.4 Method Declarations
477 * @jls 9.6.1 Annotation Type Elements
478 */
479 @Override
480 public String toGenericString() {
481 return sharedToGenericString(Modifier.methodModifiers(), isDefault());
482 }
483
484 @Override
485 void specificToGenericStringHeader(StringBuilder sb) {
486 Type genRetType = getGenericReturnType();
487 sb.append(genRetType.getTypeName()).append(' ');
488 sb.append(getDeclaringClass().getTypeName()).append('.');
489 sb.append(getName());
490 }
491
492 /**
493 * Invokes the underlying method represented by this {@code Method}
494 * object, on the specified object with the specified parameters.
495 * Individual parameters are automatically unwrapped to match
496 * primitive formal parameters, and both primitive and reference
497 * parameters are subject to method invocation conversions as
498 * necessary.
499 *
500 * <p>If the underlying method is static, then the specified {@code obj}
501 * argument is ignored. It may be null.
502 *
503 * <p>If the number of formal parameters required by the underlying method is
504 * 0, the supplied {@code args} array may be of length 0 or null.
505 *
506 * <p>If the underlying method is an instance method, it is invoked
507 * using dynamic method lookup as documented in The Java Language
508 * Specification, section 15.12.4.4; in particular,
509 * overriding based on the runtime type of the target object may occur.
510 *
511 * <p>If the underlying method is static, the class that declared
512 * the method is initialized if it has not already been initialized.
513 *
514 * <p>If the method completes normally, the value it returns is
515 * returned to the caller of invoke; if the value has a primitive
516 * type, it is first appropriately wrapped in an object. However,
517 * if the value has the type of an array of a primitive type, the
518 * elements of the array are <i>not</i> wrapped in objects; in
519 * other words, an array of primitive type is returned. If the
520 * underlying method return type is void, the invocation returns
521 * null.
522 *
523 * @param obj the object the underlying method is invoked from
524 * @param args the arguments used for the method call
525 * @return the result of dispatching the method represented by
526 * this object on {@code obj} with parameters
527 * {@code args}
528 *
529 * @exception IllegalAccessException if this {@code Method} object
530 * is enforcing Java language access control and the underlying
531 * method is inaccessible.
532 * @exception IllegalArgumentException if the method is an
533 * instance method and the specified object argument
534 * is not an instance of the class or interface
535 * declaring the underlying method (or of a subclass
536 * or implementor thereof); if the number of actual
537 * and formal parameters differ; if an unwrapping
538 * conversion for primitive arguments fails; or if,
539 * after possible unwrapping, a parameter value
540 * cannot be converted to the corresponding formal
541 * parameter type by a method invocation conversion.
542 * @exception InvocationTargetException if the underlying method
543 * throws an exception.
544 * @exception NullPointerException if the specified object is null
545 * and the method is an instance method.
546 * @exception ExceptionInInitializerError if the initialization
547 * provoked by this method fails.
548 */
549 @CallerSensitive
550 @ForceInline // to ensure Reflection.getCallerClass optimization
551 @HotSpotIntrinsicCandidate
552 public Object invoke(Object obj, Object... args)
553 throws IllegalAccessException, IllegalArgumentException,
554 InvocationTargetException
555 {
556 if (!override) {
557 Class<?> caller = Reflection.getCallerClass();
558 checkAccess(caller, clazz,
559 Modifier.isStatic(modifiers) ? null : obj.getClass(),
560 modifiers);
561 }
562 MethodAccessor ma = methodAccessor; // read volatile
563 if (ma == null) {
564 ma = acquireMethodAccessor();
565 }
566 return ma.invoke(obj, args);
567 }
568
569 /**
570 * Returns {@code true} if this method is a bridge
571 * method; returns {@code false} otherwise.
572 *
573 * @return true if and only if this method is a bridge
574 * method as defined by the Java Language Specification.
575 * @since 1.5
576 */
577 public boolean isBridge() {
578 return (getModifiers() & Modifier.BRIDGE) != 0;
579 }
580
581 /**
582 * {@inheritDoc}
583 * @since 1.5
584 */
585 @Override
586 public boolean isVarArgs() {
587 return super.isVarArgs();
588 }
589
590 /**
591 * {@inheritDoc}
592 * @jls 13.1 The Form of a Binary
593 * @since 1.5
594 */
595 @Override
596 public boolean isSynthetic() {
597 return super.isSynthetic();
598 }
599
600 /**
601 * Returns {@code true} if this method is a default
602 * method; returns {@code false} otherwise.
603 *
604 * A default method is a public non-abstract instance method, that
605 * is, a non-static method with a body, declared in an interface
606 * type.
607 *
608 * @return true if and only if this method is a default
609 * method as defined by the Java Language Specification.
610 * @since 1.8
611 */
612 public boolean isDefault() {
613 // Default methods are public non-abstract instance methods
614 // declared in an interface.
615 return ((getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) ==
616 Modifier.PUBLIC) && getDeclaringClass().isInterface();
617 }
618
619 // NOTE that there is no synchronization used here. It is correct
620 // (though not efficient) to generate more than one MethodAccessor
621 // for a given Method. However, avoiding synchronization will
622 // probably make the implementation more scalable.
623 private MethodAccessor acquireMethodAccessor() {
624 // First check to see if one has been created yet, and take it
625 // if so
626 MethodAccessor tmp = null;
627 if (root != null) tmp = root.getMethodAccessor();
628 if (tmp != null) {
629 methodAccessor = tmp;
630 } else {
631 // Otherwise fabricate one and propagate it up to the root
632 tmp = reflectionFactory.newMethodAccessor(this);
633 setMethodAccessor(tmp);
634 }
635
636 return tmp;
637 }
638
639 // Returns MethodAccessor for this Method object, not looking up
640 // the chain to the root
641 MethodAccessor getMethodAccessor() {
642 return methodAccessor;
643 }
644
645 // Sets the MethodAccessor for this Method object and
646 // (recursively) its root
647 void setMethodAccessor(MethodAccessor accessor) {
648 methodAccessor = accessor;
649 // Propagate up
650 if (root != null) {
651 root.setMethodAccessor(accessor);
652 }
653 }
654
655 /**
656 * Returns the default value for the annotation member represented by
657 * this {@code Method} instance. If the member is of a primitive type,
658 * an instance of the corresponding wrapper type is returned. Returns
659 * null if no default is associated with the member, or if the method
660 * instance does not represent a declared member of an annotation type.
661 *
662 * @return the default value for the annotation member represented
663 * by this {@code Method} instance.
664 * @throws TypeNotPresentException if the annotation is of type
665 * {@link Class} and no definition can be found for the
666 * default class value.
667 * @since 1.5
668 */
669 public Object getDefaultValue() {
670 if (annotationDefault == null)
671 return null;
672 Class<?> memberType = AnnotationType.invocationHandlerReturnType(
673 getReturnType());
674 Object result = AnnotationParser.parseMemberValue(
675 memberType, ByteBuffer.wrap(annotationDefault),
676 SharedSecrets.getJavaLangAccess().
677 getConstantPool(getDeclaringClass()),
678 getDeclaringClass());
679 if (result instanceof ExceptionProxy) {
680 if (result instanceof TypeNotPresentExceptionProxy) {
681 TypeNotPresentExceptionProxy proxy = (TypeNotPresentExceptionProxy)result;
682 throw new TypeNotPresentException(proxy.typeName(), proxy.getCause());
683 }
684 throw new AnnotationFormatError("Invalid default: " + this);
685 }
686 return result;
687 }
688
689 /**
690 * {@inheritDoc}
691 * @throws NullPointerException {@inheritDoc}
692 * @since 1.5
693 */
694 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
695 return super.getAnnotation(annotationClass);
696 }
697
698 /**
699 * {@inheritDoc}
700 * @since 1.5
701 */
702 public Annotation[] getDeclaredAnnotations() {
703 return super.getDeclaredAnnotations();
704 }
705
706 /**
707 * {@inheritDoc}
708 * @since 1.5
709 */
710 @Override
711 public Annotation[][] getParameterAnnotations() {
712 return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
713 }
714
715 /**
716 * {@inheritDoc}
717 * @since 1.8
718 */
719 @Override
720 public AnnotatedType getAnnotatedReturnType() {
721 return getAnnotatedReturnType0(getGenericReturnType());
722 }
723
724 @Override
725 boolean handleParameterNumberMismatch(int resultLength, int numParameters) {
726 throw new AnnotationFormatError("Parameter annotations don't match number of parameters");
727 }
728 }
729