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