1 /*
   2  * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.reflect;
  27 
  28 import jdk.internal.access.SharedSecrets;
  29 import jdk.internal.reflect.CallerSensitive;
  30 import jdk.internal.reflect.ConstructorAccessor;
  31 import jdk.internal.reflect.Reflection;
  32 import jdk.internal.vm.annotation.ForceInline;
  33 import sun.reflect.annotation.TypeAnnotation;
  34 import sun.reflect.annotation.TypeAnnotationParser;
  35 import sun.reflect.generics.repository.ConstructorRepository;
  36 import sun.reflect.generics.factory.CoreReflectionFactory;
  37 import sun.reflect.generics.factory.GenericsFactory;
  38 import sun.reflect.generics.scope.ConstructorScope;
  39 import java.lang.annotation.Annotation;
  40 import java.lang.annotation.AnnotationFormatError;
  41 import java.util.StringJoiner;
  42 
  43 /**
  44  * {@code Constructor} provides information about, and access to, a single
  45  * constructor for a class.
  46  *
  47  * <p>{@code Constructor} permits widening conversions to occur when matching the
  48  * actual parameters to newInstance() with the underlying
  49  * constructor's formal parameters, but throws an
  50  * {@code IllegalArgumentException} if a narrowing conversion would occur.
  51  *
  52  * @param <T> the class in which the constructor is declared
  53  *
  54  * @see Member
  55  * @see java.lang.Class
  56  * @see java.lang.Class#getConstructors()
  57  * @see java.lang.Class#getConstructor(Class[])
  58  * @see java.lang.Class#getDeclaredConstructors()
  59  *
  60  * @author      Kenneth Russell
  61  * @author      Nakul Saraiya
  62  * @since 1.1
  63  */
  64 public final class Constructor<T> extends Executable {
  65     private Class<T>            clazz;
  66     private int                 slot;
  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 ConstructorRepository genericInfo;
  74     private byte[]              annotations;
  75     private byte[]              parameterAnnotations;
  76 
  77     // Generics infrastructure
  78     // Accessor for factory
  79     private GenericsFactory getFactory() {
  80         // create scope and factory
  81         return CoreReflectionFactory.make(this, ConstructorScope.make(this));
  82     }
  83 
  84     // Accessor for generic info repository
  85     @Override
  86     ConstructorRepository getGenericInfo() {
  87         // lazily initialize repository if necessary
  88         if (genericInfo == null) {
  89             // create and cache generic info repository
  90             genericInfo =
  91                 ConstructorRepository.make(getSignature(),
  92                                            getFactory());
  93         }
  94         return genericInfo; //return cached repository
  95     }
  96 
  97     private volatile ConstructorAccessor constructorAccessor;
  98     // For sharing of ConstructorAccessors. This branching structure
  99     // is currently only two levels deep (i.e., one root Constructor
 100     // and potentially many Constructor objects pointing to it.)
 101     //
 102     // If this branching structure would ever contain cycles, deadlocks can
 103     // occur in annotation code.
 104     private Constructor<T>      root;
 105 
 106     @Override
 107     Constructor<T> getRoot() {
 108         return root;
 109     }
 110 
 111     /**
 112      * Package-private constructor used by ReflectAccess to enable
 113      * instantiation of these objects in Java code from the java.lang
 114      * package via sun.reflect.LangReflectAccess.
 115      */
 116     Constructor(Class<T> declaringClass,
 117                 Class<?>[] parameterTypes,
 118                 Class<?>[] checkedExceptions,
 119                 int modifiers,
 120                 int slot,
 121                 String signature,
 122                 byte[] annotations,
 123                 byte[] parameterAnnotations) {
 124         this.clazz = declaringClass;
 125         this.parameterTypes = parameterTypes;
 126         this.exceptionTypes = checkedExceptions;
 127         this.modifiers = modifiers;
 128         this.slot = slot;
 129         this.signature = signature;
 130         this.annotations = annotations;
 131         this.parameterAnnotations = parameterAnnotations;
 132     }
 133 
 134     /**
 135      * Package-private routine (exposed to java.lang.Class via
 136      * ReflectAccess) which returns a copy of this Constructor. The copy's
 137      * "root" field points to this Constructor.
 138      */
 139     Constructor<T> copy() {
 140         // This routine enables sharing of ConstructorAccessor objects
 141         // among Constructor 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         if (this.root != null)
 148             throw new IllegalArgumentException("Can not copy a non-root Constructor");
 149 
 150         Constructor<T> res = new Constructor<>(clazz,
 151                                                parameterTypes,
 152                                                exceptionTypes, modifiers, slot,
 153                                                signature,
 154                                                annotations,
 155                                                parameterAnnotations);
 156         res.root = this;
 157         // Might as well eagerly propagate this if already present
 158         res.constructorAccessor = constructorAccessor;
 159         return res;
 160     }
 161 
 162     /**
 163      * {@inheritDoc}
 164      *
 165      * <p> A {@code SecurityException} is also thrown if this object is a
 166      * {@code Constructor} object for the class {@code Class} and {@code flag}
 167      * is true. </p>
 168      *
 169      * @param flag {@inheritDoc}
 170      *
 171      * @throws InaccessibleObjectException {@inheritDoc}
 172      * @throws SecurityException if the request is denied by the security manager
 173      *         or this is a constructor for {@code java.lang.Class}
 174      *
 175      * @spec JPMS
 176      */
 177     @Override
 178     @CallerSensitive
 179     public void setAccessible(boolean flag) {
 180         AccessibleObject.checkPermission();
 181         if (flag) {
 182             checkCanSetAccessible(Reflection.getCallerClass());
 183         }
 184         setAccessible0(flag);
 185     }
 186 
 187     @Override
 188     void checkCanSetAccessible(Class<?> caller) {
 189         checkCanSetAccessible(caller, clazz);
 190         if (clazz == Class.class) {
 191             // can we change this to InaccessibleObjectException?
 192             throw new SecurityException("Cannot make a java.lang.Class"
 193                                         + " constructor accessible");
 194         }
 195     }
 196 
 197     @Override
 198     boolean hasGenericInformation() {
 199         return (getSignature() != null);
 200     }
 201 
 202     @Override
 203     byte[] getAnnotationBytes() {
 204         return annotations;
 205     }
 206 
 207     /**
 208      * Returns the {@code Class} object representing the class that
 209      * declares the constructor represented by this object.
 210      */
 211     @Override
 212     public Class<T> getDeclaringClass() {
 213         return clazz;
 214     }
 215 
 216     /**
 217      * Returns the name of this constructor, as a string.  This is
 218      * the binary name of the constructor's declaring class.
 219      */
 220     @Override
 221     public String getName() {
 222         return getDeclaringClass().getName();
 223     }
 224 
 225     /**
 226      * {@inheritDoc}
 227      */
 228     @Override
 229     public int getModifiers() {
 230         return modifiers;
 231     }
 232 
 233     /**
 234      * {@inheritDoc}
 235      * @throws GenericSignatureFormatError {@inheritDoc}
 236      * @since 1.5
 237      */
 238     @Override
 239     @SuppressWarnings({"rawtypes", "unchecked"})
 240     public TypeVariable<Constructor<T>>[] getTypeParameters() {
 241       if (getSignature() != null) {
 242         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
 243       } else
 244           return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
 245     }
 246 
 247 
 248     @Override
 249     Class<?>[] getSharedParameterTypes() {
 250         return parameterTypes;
 251     }
 252 
 253     @Override
 254     Class<?>[] getSharedExceptionTypes() {
 255         return exceptionTypes;
 256     }
 257 
 258     /**
 259      * {@inheritDoc}
 260      */
 261     @Override
 262     public Class<?>[] getParameterTypes() {
 263         return parameterTypes.clone();
 264     }
 265 
 266     /**
 267      * {@inheritDoc}
 268      * @since 1.8
 269      */
 270     public int getParameterCount() { return parameterTypes.length; }
 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[] getGenericParameterTypes() {
 281         return super.getGenericParameterTypes();
 282     }
 283 
 284     /**
 285      * {@inheritDoc}
 286      */
 287     @Override
 288     public Class<?>[] getExceptionTypes() {
 289         return exceptionTypes.clone();
 290     }
 291 
 292 
 293     /**
 294      * {@inheritDoc}
 295      * @throws GenericSignatureFormatError {@inheritDoc}
 296      * @throws TypeNotPresentException {@inheritDoc}
 297      * @throws MalformedParameterizedTypeException {@inheritDoc}
 298      * @since 1.5
 299      */
 300     @Override
 301     public Type[] getGenericExceptionTypes() {
 302         return super.getGenericExceptionTypes();
 303     }
 304 
 305     /**
 306      * Compares this {@code Constructor} against the specified object.
 307      * Returns true if the objects are the same.  Two {@code Constructor} objects are
 308      * the same if they were declared by the same class and have the
 309      * same formal parameter types.
 310      */
 311     public boolean equals(Object obj) {
 312         if (obj != null && obj instanceof Constructor) {
 313             Constructor<?> other = (Constructor<?>)obj;
 314             if (getDeclaringClass() == other.getDeclaringClass()) {
 315                 return equalParamTypes(parameterTypes, other.parameterTypes);
 316             }
 317         }
 318         return false;
 319     }
 320 
 321     /**
 322      * Returns a hashcode for this {@code Constructor}. The hashcode is
 323      * the same as the hashcode for the underlying constructor's
 324      * declaring class name.
 325      */
 326     public int hashCode() {
 327         return getDeclaringClass().getName().hashCode();
 328     }
 329 
 330     /**
 331      * Returns a string describing this {@code Constructor}.  The string is
 332      * formatted as the constructor access modifiers, if any,
 333      * followed by the fully-qualified name of the declaring class,
 334      * followed by a parenthesized, comma-separated list of the
 335      * constructor's formal parameter types.  For example:
 336      * <pre>{@code
 337      *    public java.util.Hashtable(int,float)
 338      * }</pre>
 339      *
 340      * <p>If the constructor is declared to throw exceptions, the
 341      * parameter list is followed by a space, followed by the word
 342      * "{@code throws}" followed by a comma-separated list of the
 343      * thrown exception types.
 344      *
 345      * <p>The only possible modifiers for constructors are the access
 346      * modifiers {@code public}, {@code protected} or
 347      * {@code private}.  Only one of these may appear, or none if the
 348      * constructor has default (package) access.
 349      *
 350      * @return a string describing this {@code Constructor}
 351      * @jls 8.8.3 Constructor Modifiers
 352      * @jls 8.9.2 Enum Body Declarations
 353      */
 354     public String toString() {
 355         return sharedToString(Modifier.constructorModifiers(),
 356                               false,
 357                               parameterTypes,
 358                               exceptionTypes);
 359     }
 360 
 361     @Override
 362     void specificToStringHeader(StringBuilder sb) {
 363         sb.append(getDeclaringClass().getTypeName());
 364     }
 365 
 366     @Override
 367     String toShortString() {
 368         StringBuilder sb = new StringBuilder("constructor ");
 369         sb.append(getDeclaringClass().getTypeName());
 370         sb.append('(');
 371         StringJoiner sj = new StringJoiner(",");
 372         for (Class<?> parameterType : getParameterTypes()) {
 373             sj.add(parameterType.getTypeName());
 374         }
 375         sb.append(sj);
 376         sb.append(')');
 377         return sb.toString();
 378     }
 379 
 380     /**
 381      * Returns a string describing this {@code Constructor},
 382      * including type parameters.  The string is formatted as the
 383      * constructor access modifiers, if any, followed by an
 384      * angle-bracketed comma separated list of the constructor's type
 385      * parameters, if any, followed by the fully-qualified name of the
 386      * declaring class, followed by a parenthesized, comma-separated
 387      * list of the constructor's generic formal parameter types.
 388      *
 389      * If this constructor was declared to take a variable number of
 390      * arguments, instead of denoting the last parameter as
 391      * "<code><i>Type</i>[]</code>", it is denoted as
 392      * "<code><i>Type</i>...</code>".
 393      *
 394      * A space is used to separate access modifiers from one another
 395      * and from the type parameters or class name.  If there are no
 396      * type parameters, the type parameter list is elided; if the type
 397      * parameter list is present, a space separates the list from the
 398      * class name.  If the constructor is declared to throw
 399      * exceptions, the parameter list is followed by a space, followed
 400      * by the word "{@code throws}" followed by a
 401      * comma-separated list of the generic thrown exception types.
 402      *
 403      * <p>The only possible modifiers for constructors are the access
 404      * modifiers {@code public}, {@code protected} or
 405      * {@code private}.  Only one of these may appear, or none if the
 406      * constructor has default (package) access.
 407      *
 408      * @return a string describing this {@code Constructor},
 409      * include type parameters
 410      *
 411      * @since 1.5
 412      * @jls 8.8.3 Constructor Modifiers
 413      * @jls 8.9.2 Enum Body Declarations
 414      */
 415     @Override
 416     public String toGenericString() {
 417         return sharedToGenericString(Modifier.constructorModifiers(), false);
 418     }
 419 
 420     @Override
 421     void specificToGenericStringHeader(StringBuilder sb) {
 422         specificToStringHeader(sb);
 423     }
 424 
 425     /**
 426      * Uses the constructor represented by this {@code Constructor} object to
 427      * create and initialize a new instance of the constructor's
 428      * declaring class, with the specified initialization parameters.
 429      * Individual parameters are automatically unwrapped to match
 430      * primitive formal parameters, and both primitive and reference
 431      * parameters are subject to method invocation conversions as necessary.
 432      *
 433      * <p>If the number of formal parameters required by the underlying constructor
 434      * is 0, the supplied {@code initargs} array may be of length 0 or null.
 435      *
 436      * <p>If the constructor's declaring class is an inner class in a
 437      * non-static context, the first argument to the constructor needs
 438      * to be the enclosing instance; see section 15.9.3 of
 439      * <cite>The Java&trade; Language Specification</cite>.
 440      *
 441      * <p>If the required access and argument checks succeed and the
 442      * instantiation will proceed, the constructor's declaring class
 443      * is initialized if it has not already been initialized.
 444      *
 445      * <p>If the constructor completes normally, returns the newly
 446      * created and initialized instance.
 447      *
 448      * @param initargs array of objects to be passed as arguments to
 449      * the constructor call; values of primitive types are wrapped in
 450      * a wrapper object of the appropriate type (e.g. a {@code float}
 451      * in a {@link java.lang.Float Float})
 452      *
 453      * @return a new object created by calling the constructor
 454      * this object represents
 455      *
 456      * @exception IllegalAccessException    if this {@code Constructor} object
 457      *              is enforcing Java language access control and the underlying
 458      *              constructor is inaccessible.
 459      * @exception IllegalArgumentException  if the number of actual
 460      *              and formal parameters differ; if an unwrapping
 461      *              conversion for primitive arguments fails; or if,
 462      *              after possible unwrapping, a parameter value
 463      *              cannot be converted to the corresponding formal
 464      *              parameter type by a method invocation conversion; if
 465      *              this constructor pertains to an enum type.
 466      * @exception InstantiationException    if the class that declares the
 467      *              underlying constructor represents an abstract class.
 468      * @exception InvocationTargetException if the underlying constructor
 469      *              throws an exception.
 470      * @exception ExceptionInInitializerError if the initialization provoked
 471      *              by this method fails.
 472      */
 473     @CallerSensitive
 474     @ForceInline // to ensure Reflection.getCallerClass optimization
 475     public T newInstance(Object ... initargs)
 476         throws InstantiationException, IllegalAccessException,
 477                IllegalArgumentException, InvocationTargetException
 478     {
 479         if (!override) {
 480             Class<?> caller = Reflection.getCallerClass();
 481             checkAccess(caller, clazz, clazz, modifiers);
 482         }
 483         if ((clazz.getModifiers() & Modifier.ENUM) != 0)
 484             throw new IllegalArgumentException("Cannot reflectively create enum objects");
 485         ConstructorAccessor ca = constructorAccessor;   // read volatile
 486         if (ca == null) {
 487             ca = acquireConstructorAccessor();
 488         }
 489         @SuppressWarnings("unchecked")
 490         T inst = (T) ca.newInstance(initargs);
 491         return inst;
 492     }
 493 
 494     /**
 495      * {@inheritDoc}
 496      * @since 1.5
 497      */
 498     @Override
 499     public boolean isVarArgs() {
 500         return super.isVarArgs();
 501     }
 502 
 503     /**
 504      * {@inheritDoc}
 505      * @jls 13.1 The Form of a Binary
 506      * @since 1.5
 507      */
 508     @Override
 509     public boolean isSynthetic() {
 510         return super.isSynthetic();
 511     }
 512 
 513     // NOTE that there is no synchronization used here. It is correct
 514     // (though not efficient) to generate more than one
 515     // ConstructorAccessor for a given Constructor. However, avoiding
 516     // synchronization will probably make the implementation more
 517     // scalable.
 518     private ConstructorAccessor acquireConstructorAccessor() {
 519         // First check to see if one has been created yet, and take it
 520         // if so.
 521         ConstructorAccessor tmp = null;
 522         if (root != null) tmp = root.getConstructorAccessor();
 523         if (tmp != null) {
 524             constructorAccessor = tmp;
 525         } else {
 526             // Otherwise fabricate one and propagate it up to the root
 527             tmp = reflectionFactory.newConstructorAccessor(this);
 528             setConstructorAccessor(tmp);
 529         }
 530 
 531         return tmp;
 532     }
 533 
 534     // Returns ConstructorAccessor for this Constructor object, not
 535     // looking up the chain to the root
 536     ConstructorAccessor getConstructorAccessor() {
 537         return constructorAccessor;
 538     }
 539 
 540     // Sets the ConstructorAccessor for this Constructor object and
 541     // (recursively) its root
 542     void setConstructorAccessor(ConstructorAccessor accessor) {
 543         constructorAccessor = accessor;
 544         // Propagate up
 545         if (root != null) {
 546             root.setConstructorAccessor(accessor);
 547         }
 548     }
 549 
 550     int getSlot() {
 551         return slot;
 552     }
 553 
 554     String getSignature() {
 555         return signature;
 556     }
 557 
 558     byte[] getRawAnnotations() {
 559         return annotations;
 560     }
 561 
 562     byte[] getRawParameterAnnotations() {
 563         return parameterAnnotations;
 564     }
 565 
 566 
 567     /**
 568      * {@inheritDoc}
 569      * @throws NullPointerException  {@inheritDoc}
 570      * @since 1.5
 571      */
 572     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 573         return super.getAnnotation(annotationClass);
 574     }
 575 
 576     /**
 577      * {@inheritDoc}
 578      * @since 1.5
 579      */
 580     public Annotation[] getDeclaredAnnotations()  {
 581         return super.getDeclaredAnnotations();
 582     }
 583 
 584     /**
 585      * {@inheritDoc}
 586      * @since 1.5
 587      */
 588     @Override
 589     public Annotation[][] getParameterAnnotations() {
 590         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
 591     }
 592 
 593     @Override
 594     boolean handleParameterNumberMismatch(int resultLength, int numParameters) {
 595         Class<?> declaringClass = getDeclaringClass();
 596         if (declaringClass.isEnum() ||
 597             declaringClass.isAnonymousClass() ||
 598             declaringClass.isLocalClass() )
 599             return false; // Can't do reliable parameter counting
 600         else {
 601             if (declaringClass.isMemberClass() &&
 602                 ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
 603                 resultLength + 1 == numParameters) {
 604                 return true;
 605             } else {
 606                 throw new AnnotationFormatError(
 607                           "Parameter annotations don't match number of parameters");
 608             }
 609         }
 610     }
 611 
 612     /**
 613      * {@inheritDoc}
 614      * @since 1.8
 615      */
 616     @Override
 617     public AnnotatedType getAnnotatedReturnType() {
 618         return getAnnotatedReturnType0(getDeclaringClass());
 619     }
 620 
 621     /**
 622      * {@inheritDoc}
 623      * @since 1.8
 624      */
 625     @Override
 626     public AnnotatedType getAnnotatedReceiverType() {
 627         Class<?> thisDeclClass = getDeclaringClass();
 628         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
 629 
 630         if (enclosingClass == null) {
 631             // A Constructor for a top-level class
 632             return null;
 633         }
 634 
 635         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
 636         if (outerDeclaringClass == null) {
 637             // A constructor for a local or anonymous class
 638             return null;
 639         }
 640 
 641         // Either static nested or inner class
 642         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
 643             // static nested
 644             return null;
 645         }
 646 
 647         // A Constructor for an inner class
 648         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
 649                 SharedSecrets.getJavaLangAccess().
 650                     getConstantPool(thisDeclClass),
 651                 this,
 652                 thisDeclClass,
 653                 enclosingClass,
 654                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
 655     }
 656 }