1 /*
   2  * Copyright (c) 2012, 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 java.lang.annotation.*;
  29 import java.util.Map;
  30 import java.util.Objects;
  31 import sun.reflect.annotation.AnnotationParser;
  32 import sun.reflect.annotation.AnnotationSupport;
  33 import sun.reflect.annotation.TypeAnnotationParser;
  34 import sun.reflect.annotation.TypeAnnotation;
  35 import sun.reflect.generics.repository.ConstructorRepository;
  36 
  37 /**
  38  * A shared superclass for the common functionality of {@link Method}
  39  * and {@link Constructor}.
  40  *
  41  * @since 1.8
  42  */
  43 public abstract class Executable extends AccessibleObject
  44     implements Member, GenericDeclaration {
  45     /*
  46      * Only grant package-visibility to the constructor.
  47      */
  48     Executable() {}
  49 
  50     /**
  51      * Accessor method to allow code sharing
  52      */
  53     abstract byte[] getAnnotationBytes();
  54     abstract byte[] getTypeAnnotationBytes();
  55 
  56     /**
  57      * Does the Executable have generic information.
  58      */
  59     abstract boolean hasGenericInformation();
  60 
  61     abstract ConstructorRepository getGenericInfo();
  62 
  63     boolean equalParamTypes(Class<?>[] params1, Class<?>[] params2) {
  64         /* Avoid unnecessary cloning */
  65         if (params1.length == params2.length) {
  66             for (int i = 0; i < params1.length; i++) {
  67                 if (params1[i] != params2[i])
  68                     return false;
  69             }
  70             return true;
  71         }
  72         return false;
  73     }
  74 
  75     Annotation[][] parseParameterAnnotations(byte[] parameterAnnotations) {
  76         return AnnotationParser.parseParameterAnnotations(
  77                parameterAnnotations,
  78                sun.misc.SharedSecrets.getJavaLangAccess().
  79                getConstantPool(getDeclaringClass()),
  80                getDeclaringClass());
  81     }
  82 
  83     void separateWithCommas(Class<?>[] types, StringBuilder sb) {
  84         for (int j = 0; j < types.length; j++) {
  85             sb.append(Field.getTypeName(types[j]));
  86             if (j < (types.length - 1))
  87                 sb.append(",");
  88         }
  89 
  90     }
  91 
  92     void printModifiersIfNonzero(StringBuilder sb, int mask, boolean isDefault) {
  93         int mod = getModifiers() & mask;
  94         
  95         if (mod != 0 && !isDefault) {
  96             sb.append(Modifier.toString(mod)).append(' ');
  97         } else {
  98             int access_mod = mod & Modifier.ACCESS_MODIFIERS;
  99             if (access_mod != 0)
 100                 sb.append(Modifier.toString(access_mod)).append(' ');
 101             if (isDefault)
 102                 sb.append("default ");
 103             mod = (mod & ~Modifier.ACCESS_MODIFIERS);
 104             if (mod != 0)
 105                 sb.append(Modifier.toString(mod)).append(' ');
 106         }
 107     }
 108 
 109     String sharedToString(int modifierMask,
 110                           boolean isDefault,
 111                           Class<?>[] parameterTypes,
 112                           Class<?>[] exceptionTypes) {
 113         try {
 114             StringBuilder sb = new StringBuilder();
 115 
 116             printModifiersIfNonzero(sb, modifierMask, isDefault);
 117             specificToStringHeader(sb);
 118 
 119             sb.append('(');
 120             separateWithCommas(parameterTypes, sb);
 121             sb.append(')');
 122             if (exceptionTypes.length > 0) {
 123                 sb.append(" throws ");
 124                 separateWithCommas(exceptionTypes, sb);
 125             }
 126             return sb.toString();
 127         } catch (Exception e) {
 128             return "<" + e + ">";
 129         }
 130     }
 131 
 132     /**
 133      * Generate toString header information specific to a method or
 134      * constructor.
 135      */
 136     abstract void specificToStringHeader(StringBuilder sb);
 137 
 138     String sharedToGenericString(int modifierMask, boolean isDefault) {
 139         try {
 140             StringBuilder sb = new StringBuilder();
 141 
 142             printModifiersIfNonzero(sb, modifierMask, isDefault);
 143 
 144             TypeVariable<?>[] typeparms = getTypeParameters();
 145             if (typeparms.length > 0) {
 146                 boolean first = true;
 147                 sb.append('<');
 148                 for(TypeVariable<?> typeparm: typeparms) {
 149                     if (!first)
 150                         sb.append(',');
 151                     // Class objects can't occur here; no need to test
 152                     // and call Class.getName().
 153                     sb.append(typeparm.toString());
 154                     first = false;
 155                 }
 156                 sb.append("> ");
 157             }
 158 
 159             specificToGenericStringHeader(sb);
 160 
 161             sb.append('(');
 162             Type[] params = getGenericParameterTypes();
 163             for (int j = 0; j < params.length; j++) {
 164                 String param = (params[j] instanceof Class)?
 165                     Field.getTypeName((Class)params[j]):
 166                     (params[j].toString());
 167                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
 168                     param = param.replaceFirst("\\[\\]$", "...");
 169                 sb.append(param);
 170                 if (j < (params.length - 1))
 171                     sb.append(',');
 172             }
 173             sb.append(')');
 174             Type[] exceptions = getGenericExceptionTypes();
 175             if (exceptions.length > 0) {
 176                 sb.append(" throws ");
 177                 for (int k = 0; k < exceptions.length; k++) {
 178                     sb.append((exceptions[k] instanceof Class)?
 179                               ((Class)exceptions[k]).getName():
 180                               exceptions[k].toString());
 181                     if (k < (exceptions.length - 1))
 182                         sb.append(',');
 183                 }
 184             }
 185             return sb.toString();
 186         } catch (Exception e) {
 187             return "<" + e + ">";
 188         }
 189     }
 190 
 191     /**
 192      * Generate toGenericString header information specific to a
 193      * method or constructor.
 194      */
 195     abstract void specificToGenericStringHeader(StringBuilder sb);
 196 
 197     /**
 198      * Returns the {@code Class} object representing the class or interface
 199      * that declares the executable represented by this object.
 200      */
 201     public abstract Class<?> getDeclaringClass();
 202 
 203     /**
 204      * Returns the name of the executable represented by this object.
 205      */
 206     public abstract String getName();
 207 
 208     /**
 209      * Returns the Java language {@linkplain Modifier modifiers} for
 210      * the executable represented by this object.
 211      */
 212     public abstract int getModifiers();
 213 
 214     /**
 215      * Returns an array of {@code TypeVariable} objects that represent the
 216      * type variables declared by the generic declaration represented by this
 217      * {@code GenericDeclaration} object, in declaration order.  Returns an
 218      * array of length 0 if the underlying generic declaration declares no type
 219      * variables.
 220      *
 221      * @return an array of {@code TypeVariable} objects that represent
 222      *     the type variables declared by this generic declaration
 223      * @throws GenericSignatureFormatError if the generic
 224      *     signature of this generic declaration does not conform to
 225      *     the format specified in
 226      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 227      */
 228     public abstract TypeVariable<?>[] getTypeParameters();
 229 
 230     /**
 231      * Returns an array of {@code Class} objects that represent the formal
 232      * parameter types, in declaration order, of the executable
 233      * represented by this object.  Returns an array of length
 234      * 0 if the underlying executable takes no parameters.
 235      *
 236      * @return the parameter types for the executable this object
 237      * represents
 238      */
 239     public abstract Class<?>[] getParameterTypes();
 240 
 241     /**
 242      * Returns the number of formal parameters (including any
 243      * synthetic or synthesized parameters) for the executable
 244      * represented by this object.
 245      *
 246      * @return The number of formal parameters for the executable this
 247      * object represents
 248      */
 249     public int getParameterCount() {
 250         throw new AbstractMethodError();
 251     }
 252 
 253     /**
 254      * Returns an array of {@code Type} objects that represent the formal
 255      * parameter types, in declaration order, of the executable represented by
 256      * this object. Returns an array of length 0 if the
 257      * underlying executable takes no parameters.
 258      *
 259      * <p>If a formal parameter type is a parameterized type,
 260      * the {@code Type} object returned for it must accurately reflect
 261      * the actual type parameters used in the source code.
 262      *
 263      * <p>If a formal parameter type is a type variable or a parameterized
 264      * type, it is created. Otherwise, it is resolved.
 265      *
 266      * @return an array of {@code Type}s that represent the formal
 267      *     parameter types of the underlying executable, in declaration order
 268      * @throws GenericSignatureFormatError
 269      *     if the generic method signature does not conform to the format
 270      *     specified in
 271      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 272      * @throws TypeNotPresentException if any of the parameter
 273      *     types of the underlying executable refers to a non-existent type
 274      *     declaration
 275      * @throws MalformedParameterizedTypeException if any of
 276      *     the underlying executable's parameter types refer to a parameterized
 277      *     type that cannot be instantiated for any reason
 278      */
 279     public Type[] getGenericParameterTypes() {
 280         if (hasGenericInformation())
 281             return getGenericInfo().getParameterTypes();
 282         else
 283             return getParameterTypes();
 284     }
 285 
 286     /**
 287      * Returns an array of {@code Parameter} objects that represent
 288      * all the parameters to the underlying executable represented by
 289      * this object.  Returns an array of length 0 if the executable
 290      * has no parameters.
 291      *
 292      * The parameters of the underlying executable do not necessarily
 293      * have unique names, or names that are legal identifiers in the
 294      * Java programming language (JLS 3.8).
 295      *
 296      * @return an array of {@code Parameter} objects representing all
 297      * the parameters to the executable this object represents
 298      */
 299     public Parameter[] getParameters() {
 300         // TODO: This may eventually need to be guarded by security
 301         // mechanisms similar to those in Field, Method, etc.
 302         //
 303         // Need to copy the cached array to prevent users from messing
 304         // with it.  Since parameters are immutable, we can
 305         // shallow-copy.
 306         return privateGetParameters().clone();
 307     }
 308 
 309     private Parameter[] synthesizeAllParams() {
 310         final int realparams = getParameterCount();
 311         final Parameter[] out = new Parameter[realparams];
 312         for (int i = 0; i < realparams; i++)
 313             // TODO: is there a way to synthetically derive the
 314             // modifiers?  Probably not in the general case, since
 315             // we'd have no way of knowing about them, but there
 316             // may be specific cases.
 317             out[i] = new Parameter("arg" + i, 0, this, i);
 318         return out;
 319     }
 320 
 321     private Parameter[] privateGetParameters() {
 322         // Use tmp to avoid multiple writes to a volatile.
 323         Parameter[] tmp = parameters;
 324 
 325         if (tmp == null) {
 326 
 327             // Otherwise, go to the JVM to get them
 328             tmp = getParameters0();
 329 
 330             // If we get back nothing, then synthesize parameters
 331             if (tmp == null)
 332                 tmp = synthesizeAllParams();
 333 
 334             parameters = tmp;
 335         }
 336 
 337         return tmp;
 338     }
 339 
 340     private transient volatile Parameter[] parameters;
 341 
 342     private native Parameter[] getParameters0();
 343 
 344     /**
 345      * Returns an array of {@code Class} objects that represent the
 346      * types of exceptions declared to be thrown by the underlying
 347      * executable represented by this object.  Returns an array of
 348      * length 0 if the executable declares no exceptions in its {@code
 349      * throws} clause.
 350      *
 351      * @return the exception types declared as being thrown by the
 352      * executable this object represents
 353      */
 354     public abstract Class<?>[] getExceptionTypes();
 355 
 356     /**
 357      * Returns an array of {@code Type} objects that represent the
 358      * exceptions declared to be thrown by this executable object.
 359      * Returns an array of length 0 if the underlying executable declares
 360      * no exceptions in its {@code throws} clause.
 361      *
 362      * <p>If an exception type is a type variable or a parameterized
 363      * type, it is created. Otherwise, it is resolved.
 364      *
 365      * @return an array of Types that represent the exception types
 366      *     thrown by the underlying executable
 367      * @throws GenericSignatureFormatError
 368      *     if the generic method signature does not conform to the format
 369      *     specified in
 370      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 371      * @throws TypeNotPresentException if the underlying executable's
 372      *     {@code throws} clause refers to a non-existent type declaration
 373      * @throws MalformedParameterizedTypeException if
 374      *     the underlying executable's {@code throws} clause refers to a
 375      *     parameterized type that cannot be instantiated for any reason
 376      */
 377     public Type[] getGenericExceptionTypes() {
 378         Type[] result;
 379         if (hasGenericInformation() &&
 380             ((result = getGenericInfo().getExceptionTypes()).length > 0))
 381             return result;
 382         else
 383             return getExceptionTypes();
 384     }
 385 
 386     /**
 387      * Returns a string describing this {@code Executable}, including
 388      * any type parameters.
 389      */
 390     public abstract String toGenericString();
 391 
 392     /**
 393      * Returns {@code true} if this executable was declared to take a
 394      * variable number of arguments; returns {@code false} otherwise.
 395      *
 396      * @return {@code true} if an only if this executable was declared
 397      * to take a variable number of arguments.
 398      */
 399     public boolean isVarArgs()  {
 400         return (getModifiers() & Modifier.VARARGS) != 0;
 401     }
 402 
 403     /**
 404      * Returns {@code true} if this executable is a synthetic
 405      * construct; returns {@code false} otherwise.
 406      *
 407      * @return true if and only if this executable is a synthetic
 408      * construct as defined by
 409      * <cite>The Java&trade; Language Specification</cite>.
 410      * @jls 13.1 The Form of a Binary
 411      */
 412     public boolean isSynthetic() {
 413         return Modifier.isSynthetic(getModifiers());
 414     }
 415 
 416     /**
 417      * Returns an array of arrays that represent the annotations on
 418      * the formal parameters, in declaration order, of the executable
 419      * represented by this object. (Returns an array of length zero if
 420      * the underlying executable is parameterless.  If the executable has
 421      * one or more parameters, a nested array of length zero is
 422      * returned for each parameter with no annotations.) The
 423      * annotation objects contained in the returned arrays are
 424      * serializable.  The caller of this method is free to modify the
 425      * returned arrays; it will have no effect on the arrays returned
 426      * to other callers.
 427      *
 428      * @return an array of arrays that represent the annotations on the formal
 429      *    parameters, in declaration order, of the executable represented by this
 430      *    object
 431      */
 432     public abstract Annotation[][] getParameterAnnotations();
 433 
 434     Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes,
 435                                                  byte[] parameterAnnotations) {
 436         int numParameters = parameterTypes.length;
 437         if (parameterAnnotations == null)
 438             return new Annotation[numParameters][0];
 439 
 440         Annotation[][] result = parseParameterAnnotations(parameterAnnotations);
 441 
 442         if (result.length != numParameters)
 443             handleParameterNumberMismatch(result.length, numParameters);
 444         return result;
 445     }
 446 
 447     abstract void handleParameterNumberMismatch(int resultLength, int numParameters);
 448 
 449     /**
 450      * {@inheritDoc}
 451      * @throws NullPointerException  {@inheritDoc}
 452      */
 453     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 454         Objects.requireNonNull(annotationClass);
 455         return annotationClass.cast(declaredAnnotations().get(annotationClass));
 456     }
 457 
 458     /**
 459      * {@inheritDoc}
 460      * @throws NullPointerException {@inheritDoc}
 461      * @since 1.8
 462      */
 463     @Override
 464     public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
 465         Objects.requireNonNull(annotationClass);
 466 
 467         return AnnotationSupport.getMultipleAnnotations(declaredAnnotations(), annotationClass);
 468     }
 469 
 470     /**
 471      * {@inheritDoc}
 472      */
 473     public Annotation[] getDeclaredAnnotations()  {
 474         return AnnotationParser.toArray(declaredAnnotations());
 475     }
 476 
 477     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
 478 
 479     private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
 480         if (declaredAnnotations == null) {
 481             declaredAnnotations = AnnotationParser.parseAnnotations(
 482                 getAnnotationBytes(),
 483                 sun.misc.SharedSecrets.getJavaLangAccess().
 484                 getConstantPool(getDeclaringClass()),
 485                 getDeclaringClass());
 486         }
 487         return declaredAnnotations;
 488     }
 489 
 490     /**
 491      * Returns an AnnotatedType object that represents the potentially
 492      * annotated return type of the method/constructor represented by this
 493      * Executable.
 494      *
 495      * If this Executable represents a constructor, the AnnotatedType object
 496      * represents the type of the constructed object.
 497      *
 498      * If this Executable represents a method, the AnnotatedType object
 499      * represents the use of a type to specify the return type of the method.
 500      *
 501      * @since 1.8
 502      */
 503     public abstract AnnotatedType getAnnotatedReturnType();
 504 
 505     /* Helper for subclasses of Executable.
 506      *
 507      * Returns an AnnotatedType object that represents the use of a type to
 508      * specify the return type of the method/constructor represented by this
 509      * Executable.
 510      *
 511      * @since 1.8
 512      */
 513     AnnotatedType getAnnotatedReturnType0(Type returnType) {
 514         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes(),
 515                                                        sun.misc.SharedSecrets.getJavaLangAccess().
 516                                                            getConstantPool(getDeclaringClass()),
 517                                                        this,
 518                                                        getDeclaringClass(),
 519                                                        returnType,
 520                                                        TypeAnnotation.TypeAnnotationTarget.METHOD_RETURN_TYPE);
 521     }
 522 
 523     /**
 524      * Returns an AnnotatedType object that represents the use of a type to
 525      * specify the receiver type of the method/constructor represented by this
 526      * Executable. The receiver type of a method/constructor is available only
 527      * if the method/constructor declares a formal parameter called 'this'.
 528      *
 529      * Returns null if this Executable represents a constructor or instance
 530      * method that either declares no formal parameter called 'this', or
 531      * declares a formal parameter called 'this' with no annotations on its
 532      * type.
 533      *
 534      * Returns null if this Executable represents a static method.
 535      *
 536      * @since 1.8
 537      */
 538     public AnnotatedType getAnnotatedReceiverType() {
 539         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes(),
 540                                                        sun.misc.SharedSecrets.getJavaLangAccess().
 541                                                            getConstantPool(getDeclaringClass()),
 542                                                        this,
 543                                                        getDeclaringClass(),
 544                                                        getDeclaringClass(),
 545                                                        TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER_TYPE);
 546     }
 547 
 548     /**
 549      * Returns an array of AnnotatedType objects that represent the use of
 550      * types to specify formal parameter types of the method/constructor
 551      * represented by this Executable. The order of the objects in the array
 552      * corresponds to the order of the formal parameter types in the
 553      * declaration of the method/constructor.
 554      *
 555      * Returns an array of length 0 if the method/constructor declares no
 556      * parameters.
 557      *
 558      * @since 1.8
 559      */
 560     public AnnotatedType[] getAnnotatedParameterTypes() {
 561         throw new UnsupportedOperationException("Not yet");
 562     }
 563 
 564     /**
 565      * Returns an array of AnnotatedType objects that represent the use of
 566      * types to specify the declared exceptions of the method/constructor
 567      * represented by this Executable. The order of the objects in the array
 568      * corresponds to the order of the exception types in the declaration of
 569      * the method/constructor.
 570      *
 571      * Returns an array of length 0 if the method/constructor declares no
 572      * exceptions.
 573      *
 574      * @since 1.8
 575      */
 576     public AnnotatedType[] getAnnotatedExceptionTypes() {
 577         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes(),
 578                                                         sun.misc.SharedSecrets.getJavaLangAccess().
 579                                                             getConstantPool(getDeclaringClass()),
 580                                                         this,
 581                                                         getDeclaringClass(),
 582                                                         getGenericExceptionTypes(),
 583                                                         TypeAnnotation.TypeAnnotationTarget.THROWS);
 584     }
 585 
 586 }