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