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