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