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