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