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 
 182         if (flag) {
 183             if (clazz.isValue()) {
 184                 throw new InaccessibleObjectException(
 185                     "Unable to make an inline class constructor \"" + this + "\" accessible");
 186             }
 187             checkCanSetAccessible(Reflection.getCallerClass());
 188         }
 189         setAccessible0(flag);
 190     }
 191 
 192     @Override
 193     void checkCanSetAccessible(Class<?> caller) {
 194         checkCanSetAccessible(caller, clazz);
 195         if (clazz == Class.class) {
 196             // can we change this to InaccessibleObjectException?
 197             throw new SecurityException("Cannot make a java.lang.Class"
 198                                         + " constructor accessible");
 199         }
 200     }
 201 
 202     @Override
 203     boolean hasGenericInformation() {
 204         return (getSignature() != null);
 205     }
 206 
 207     @Override
 208     byte[] getAnnotationBytes() {
 209         return annotations;
 210     }
 211 
 212     /**
 213      * Returns the {@code Class} object representing
 214      * {@linkplain Class#asBoxType() the box type} of the class that
 215      * declares the constructor represented by this object.
 216      */
 217     @Override
 218     public Class<T> getDeclaringClass() {
 219         return clazz;
 220     }
 221 
 222     /**
 223      * Returns the name of this constructor, as a string.  This is
 224      * the binary name of the constructor's declaring class.
 225      */
 226     @Override
 227     public String getName() {
 228         return getDeclaringClass().getName();
 229     }
 230 
 231     /**
 232      * {@inheritDoc}
 233      */
 234     @Override
 235     public int getModifiers() {
 236         return modifiers;
 237     }
 238 
 239     /**
 240      * {@inheritDoc}
 241      * @throws GenericSignatureFormatError {@inheritDoc}
 242      * @since 1.5
 243      */
 244     @Override
 245     @SuppressWarnings({"rawtypes", "unchecked"})
 246     public TypeVariable<Constructor<T>>[] getTypeParameters() {
 247       if (getSignature() != null) {
 248         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
 249       } else
 250           return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
 251     }
 252 
 253 
 254     @Override
 255     Class<?>[] getSharedParameterTypes() {
 256         return parameterTypes;
 257     }
 258 
 259     @Override
 260     Class<?>[] getSharedExceptionTypes() {
 261         return exceptionTypes;
 262     }
 263 
 264     /**
 265      * {@inheritDoc}
 266      */
 267     @Override
 268     public Class<?>[] getParameterTypes() {
 269         return parameterTypes.clone();
 270     }
 271 
 272     /**
 273      * {@inheritDoc}
 274      * @since 1.8
 275      */
 276     public int getParameterCount() { return parameterTypes.length; }
 277 
 278     /**
 279      * {@inheritDoc}
 280      * @throws GenericSignatureFormatError {@inheritDoc}
 281      * @throws TypeNotPresentException {@inheritDoc}
 282      * @throws MalformedParameterizedTypeException {@inheritDoc}
 283      * @since 1.5
 284      */
 285     @Override
 286     public Type[] getGenericParameterTypes() {
 287         return super.getGenericParameterTypes();
 288     }
 289 
 290     /**
 291      * {@inheritDoc}
 292      */
 293     @Override
 294     public Class<?>[] getExceptionTypes() {
 295         return exceptionTypes.clone();
 296     }
 297 
 298 
 299     /**
 300      * {@inheritDoc}
 301      * @throws GenericSignatureFormatError {@inheritDoc}
 302      * @throws TypeNotPresentException {@inheritDoc}
 303      * @throws MalformedParameterizedTypeException {@inheritDoc}
 304      * @since 1.5
 305      */
 306     @Override
 307     public Type[] getGenericExceptionTypes() {
 308         return super.getGenericExceptionTypes();
 309     }
 310 
 311     /**
 312      * Compares this {@code Constructor} against the specified object.
 313      * Returns true if the objects are the same.  Two {@code Constructor} objects are
 314      * the same if they were declared by the same class and have the
 315      * same formal parameter types.
 316      */
 317     public boolean equals(Object obj) {
 318         if (obj != null && obj instanceof Constructor) {
 319             Constructor<?> other = (Constructor<?>)obj;
 320             if (getDeclaringClass() == other.getDeclaringClass()) {
 321                 return equalParamTypes(parameterTypes, other.parameterTypes);
 322             }
 323         }
 324         return false;
 325     }
 326 
 327     /**
 328      * Returns a hashcode for this {@code Constructor}. The hashcode is
 329      * the same as the hashcode for the underlying constructor's
 330      * declaring class name.
 331      */
 332     public int hashCode() {
 333         return getDeclaringClass().getName().hashCode();
 334     }
 335 
 336     /**
 337      * Returns a string describing this {@code Constructor}.  The string is
 338      * formatted as the constructor access modifiers, if any,
 339      * followed by the fully-qualified name of the declaring class,
 340      * followed by a parenthesized, comma-separated list of the
 341      * constructor's formal parameter types.  For example:
 342      * <pre>{@code
 343      *    public java.util.Hashtable(int,float)
 344      * }</pre>
 345      *
 346      * <p>If the constructor is declared to throw exceptions, the
 347      * parameter list is followed by a space, followed by the word
 348      * "{@code throws}" followed by a comma-separated list of the
 349      * thrown exception types.
 350      *
 351      * <p>The only possible modifiers for constructors are the access
 352      * modifiers {@code public}, {@code protected} or
 353      * {@code private}.  Only one of these may appear, or none if the
 354      * constructor has default (package) access.
 355      *
 356      * @return a string describing this {@code Constructor}
 357      * @jls 8.8.3 Constructor Modifiers
 358      * @jls 8.9.2 Enum Body Declarations
 359      */
 360     public String toString() {
 361         return sharedToString(Modifier.constructorModifiers(),
 362                               false,
 363                               parameterTypes,
 364                               exceptionTypes);
 365     }
 366 
 367     @Override
 368     void specificToStringHeader(StringBuilder sb) {
 369         sb.append(getDeclaringClass().getTypeName());
 370     }
 371 
 372     @Override
 373     String toShortString() {
 374         StringBuilder sb = new StringBuilder("constructor ");
 375         sb.append(getDeclaringClass().getTypeName());
 376         sb.append('(');
 377         StringJoiner sj = new StringJoiner(",");
 378         for (Class<?> parameterType : getParameterTypes()) {
 379             sj.add(parameterType.getTypeName());
 380         }
 381         sb.append(sj);
 382         sb.append(')');
 383         return sb.toString();
 384     }
 385 
 386     /**
 387      * Returns a string describing this {@code Constructor},
 388      * including type parameters.  The string is formatted as the
 389      * constructor access modifiers, if any, followed by an
 390      * angle-bracketed comma separated list of the constructor's type
 391      * parameters, if any, including  informative bounds of the
 392      * type parameters, if any, followed by the fully-qualified name of the
 393      * declaring class, followed by a parenthesized, comma-separated
 394      * list of the constructor's generic formal parameter types.
 395      *
 396      * If this constructor was declared to take a variable number of
 397      * arguments, instead of denoting the last parameter as
 398      * "<code><i>Type</i>[]</code>", it is denoted as
 399      * "<code><i>Type</i>...</code>".
 400      *
 401      * A space is used to separate access modifiers from one another
 402      * and from the type parameters or class name.  If there are no
 403      * type parameters, the type parameter list is elided; if the type
 404      * parameter list is present, a space separates the list from the
 405      * class name.  If the constructor is declared to throw
 406      * exceptions, the parameter list is followed by a space, followed
 407      * by the word "{@code throws}" followed by a
 408      * comma-separated list of the generic thrown exception types.
 409      *
 410      * <p>The only possible modifiers for constructors are the access
 411      * modifiers {@code public}, {@code protected} or
 412      * {@code private}.  Only one of these may appear, or none if the
 413      * constructor has default (package) access.
 414      *
 415      * @return a string describing this {@code Constructor},
 416      * include type parameters
 417      *
 418      * @since 1.5
 419      * @jls 8.8.3 Constructor Modifiers
 420      * @jls 8.9.2 Enum Body Declarations
 421      */
 422     @Override
 423     public String toGenericString() {
 424         return sharedToGenericString(Modifier.constructorModifiers(), false);
 425     }
 426 
 427     @Override
 428     void specificToGenericStringHeader(StringBuilder sb) {
 429         specificToStringHeader(sb);
 430     }
 431 
 432     /**
 433      * Uses the constructor represented by this {@code Constructor} object to
 434      * create and initialize a new instance of the constructor's
 435      * declaring class, with the specified initialization parameters.
 436      * Individual parameters are automatically unwrapped to match
 437      * primitive formal parameters, and both primitive and reference
 438      * parameters are subject to method invocation conversions as necessary.
 439      *
 440      * <p>If the number of formal parameters required by the underlying constructor
 441      * is 0, the supplied {@code initargs} array may be of length 0 or null.
 442      *
 443      * <p>If the constructor's declaring class is an inner class in a
 444      * non-static context, the first argument to the constructor needs
 445      * to be the enclosing instance; see section 15.9.3 of
 446      * <cite>The Java&trade; Language Specification</cite>.
 447      *
 448      * <p>If the required access and argument checks succeed and the
 449      * instantiation will proceed, the constructor's declaring class
 450      * is initialized if it has not already been initialized.
 451      *
 452      * <p>If the constructor completes normally, returns the newly
 453      * created and initialized instance.
 454      *
 455      * @param initargs array of objects to be passed as arguments to
 456      * the constructor call; values of primitive types are wrapped in
 457      * a wrapper object of the appropriate type (e.g. a {@code float}
 458      * in a {@link java.lang.Float Float})
 459      *
 460      * @return a new object created by calling the constructor
 461      * this object represents
 462      *
 463      * @exception IllegalAccessException    if this {@code Constructor} object
 464      *              is enforcing Java language access control and the underlying
 465      *              constructor is inaccessible.
 466      * @exception IllegalArgumentException  if the number of actual
 467      *              and formal parameters differ; if an unwrapping
 468      *              conversion for primitive arguments fails; or if,
 469      *              after possible unwrapping, a parameter value
 470      *              cannot be converted to the corresponding formal
 471      *              parameter type by a method invocation conversion; if
 472      *              this constructor pertains to an enum type.
 473      * @exception InstantiationException    if the class that declares the
 474      *              underlying constructor represents an abstract class.
 475      * @exception InvocationTargetException if the underlying constructor
 476      *              throws an exception.
 477      * @exception ExceptionInInitializerError if the initialization provoked
 478      *              by this method fails.
 479      */
 480     @CallerSensitive
 481     @ForceInline // to ensure Reflection.getCallerClass optimization
 482     public T newInstance(Object ... initargs)
 483         throws InstantiationException, IllegalAccessException,
 484                IllegalArgumentException, InvocationTargetException
 485     {
 486         if (clazz.isValue()) {
 487             throw new IllegalAccessException(
 488                 "cannot create new instance of an inline class " + clazz.getName());
 489         }
 490         Class<?> caller = override ? null : Reflection.getCallerClass();
 491         return newInstanceWithCaller(initargs, !override, caller);
 492     }
 493 
 494     /* package-private */
 495     T newInstanceWithCaller(Object[] args, boolean checkAccess, Class<?> caller)
 496         throws InstantiationException, IllegalAccessException,
 497                InvocationTargetException
 498     {
 499         if (checkAccess)
 500             checkAccess(caller, clazz, clazz, modifiers);
 501 
 502         if ((clazz.getModifiers() & Modifier.ENUM) != 0)
 503             throw new IllegalArgumentException("Cannot reflectively create enum objects");
 504 
 505         ConstructorAccessor ca = constructorAccessor;   // read volatile
 506         if (ca == null) {
 507             ca = acquireConstructorAccessor();
 508         }
 509         @SuppressWarnings("unchecked")
 510         T inst = (T) ca.newInstance(args);
 511         return inst;
 512     }
 513 
 514     /**
 515      * {@inheritDoc}
 516      * @since 1.5
 517      */
 518     @Override
 519     public boolean isVarArgs() {
 520         return super.isVarArgs();
 521     }
 522 
 523     /**
 524      * {@inheritDoc}
 525      * @jls 13.1 The Form of a Binary
 526      * @since 1.5
 527      */
 528     @Override
 529     public boolean isSynthetic() {
 530         return super.isSynthetic();
 531     }
 532 
 533     // NOTE that there is no synchronization used here. It is correct
 534     // (though not efficient) to generate more than one
 535     // ConstructorAccessor for a given Constructor. However, avoiding
 536     // synchronization will probably make the implementation more
 537     // scalable.
 538     private ConstructorAccessor acquireConstructorAccessor() {
 539         // First check to see if one has been created yet, and take it
 540         // if so.
 541         ConstructorAccessor tmp = null;
 542         if (root != null) tmp = root.getConstructorAccessor();
 543         if (tmp != null) {
 544             constructorAccessor = tmp;
 545         } else {
 546             // Otherwise fabricate one and propagate it up to the root
 547             tmp = reflectionFactory.newConstructorAccessor(this);
 548             setConstructorAccessor(tmp);
 549         }
 550 
 551         return tmp;
 552     }
 553 
 554     // Returns ConstructorAccessor for this Constructor object, not
 555     // looking up the chain to the root
 556     ConstructorAccessor getConstructorAccessor() {
 557         return constructorAccessor;
 558     }
 559 
 560     // Sets the ConstructorAccessor for this Constructor object and
 561     // (recursively) its root
 562     void setConstructorAccessor(ConstructorAccessor accessor) {
 563         constructorAccessor = accessor;
 564         // Propagate up
 565         if (root != null) {
 566             root.setConstructorAccessor(accessor);
 567         }
 568     }
 569 
 570     int getSlot() {
 571         return slot;
 572     }
 573 
 574     String getSignature() {
 575         return signature;
 576     }
 577 
 578     byte[] getRawAnnotations() {
 579         return annotations;
 580     }
 581 
 582     byte[] getRawParameterAnnotations() {
 583         return parameterAnnotations;
 584     }
 585 
 586 
 587     /**
 588      * {@inheritDoc}
 589      * @throws NullPointerException  {@inheritDoc}
 590      * @since 1.5
 591      */
 592     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 593         return super.getAnnotation(annotationClass);
 594     }
 595 
 596     /**
 597      * {@inheritDoc}
 598      * @since 1.5
 599      */
 600     public Annotation[] getDeclaredAnnotations()  {
 601         return super.getDeclaredAnnotations();
 602     }
 603 
 604     /**
 605      * {@inheritDoc}
 606      * @since 1.5
 607      */
 608     @Override
 609     public Annotation[][] getParameterAnnotations() {
 610         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
 611     }
 612 
 613     @Override
 614     boolean handleParameterNumberMismatch(int resultLength, int numParameters) {
 615         Class<?> declaringClass = getDeclaringClass();
 616         if (declaringClass.isEnum() ||
 617             declaringClass.isAnonymousClass() ||
 618             declaringClass.isLocalClass() )
 619             return false; // Can't do reliable parameter counting
 620         else {
 621             if (declaringClass.isMemberClass() &&
 622                 ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
 623                 resultLength + 1 == numParameters) {
 624                 return true;
 625             } else {
 626                 throw new AnnotationFormatError(
 627                           "Parameter annotations don't match number of parameters");
 628             }
 629         }
 630     }
 631 
 632     /**
 633      * {@inheritDoc}
 634      * @since 1.8
 635      */
 636     @Override
 637     public AnnotatedType getAnnotatedReturnType() {
 638         return getAnnotatedReturnType0(getDeclaringClass());
 639     }
 640 
 641     /**
 642      * {@inheritDoc}
 643      * @since 1.8
 644      */
 645     @Override
 646     public AnnotatedType getAnnotatedReceiverType() {
 647         Class<?> thisDeclClass = getDeclaringClass();
 648         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
 649 
 650         if (enclosingClass == null) {
 651             // A Constructor for a top-level class
 652             return null;
 653         }
 654 
 655         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
 656         if (outerDeclaringClass == null) {
 657             // A constructor for a local or anonymous class
 658             return null;
 659         }
 660 
 661         // Either static nested or inner class
 662         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
 663             // static nested
 664             return null;
 665         }
 666 
 667         // A Constructor for an inner class
 668         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
 669                 SharedSecrets.getJavaLangAccess().
 670                     getConstantPool(thisDeclClass),
 671                 this,
 672                 thisDeclClass,
 673                 enclosingClass,
 674                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
 675     }
 676 }