1 /*
   2  * Copyright (c) 1996, 2013, 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 sun.reflect.CallerSensitive;
  29 import sun.reflect.ConstructorAccessor;
  30 import sun.reflect.Reflection;
  31 import sun.reflect.annotation.TypeAnnotation;
  32 import sun.reflect.annotation.TypeAnnotationParser;
  33 import sun.reflect.generics.repository.ConstructorRepository;
  34 import sun.reflect.generics.factory.CoreReflectionFactory;
  35 import sun.reflect.generics.factory.GenericsFactory;
  36 import sun.reflect.generics.scope.ConstructorScope;
  37 import java.lang.annotation.Annotation;
  38 import java.lang.annotation.AnnotationFormatError;
  39 
  40 /**
  41  * {@code Constructor} provides information about, and access to, a single
  42  * constructor for a class.
  43  *
  44  * <p>{@code Constructor} permits widening conversions to occur when matching the
  45  * actual parameters to newInstance() with the underlying
  46  * constructor's formal parameters, but throws an
  47  * {@code IllegalArgumentException} if a narrowing conversion would occur.
  48  *
  49  * @param <T> the class in which the constructor is declared
  50  *
  51  * @see Member
  52  * @see java.lang.Class
  53  * @see java.lang.Class#getConstructors()
  54  * @see java.lang.Class#getConstructor(Class[])
  55  * @see java.lang.Class#getDeclaredConstructors()
  56  *
  57  * @author      Kenneth Russell
  58  * @author      Nakul Saraiya
  59  */
  60 public final class Constructor<T> extends Executable {
  61     private Class<T>            clazz;
  62     private int                 slot;
  63     private Class<?>[]          parameterTypes;
  64     private Class<?>[]          exceptionTypes;
  65     private int                 modifiers;
  66     // Generics and annotations support
  67     private transient String    signature;
  68     // generic info repository; lazily initialized
  69     private transient ConstructorRepository genericInfo;
  70     private byte[]              annotations;
  71     private byte[]              parameterAnnotations;
  72 
  73     // Generics infrastructure
  74     // Accessor for factory
  75     private GenericsFactory getFactory() {
  76         // create scope and factory
  77         return CoreReflectionFactory.make(this, ConstructorScope.make(this));
  78     }
  79 
  80     // Accessor for generic info repository
  81     @Override
  82     ConstructorRepository getGenericInfo() {
  83         // lazily initialize repository if necessary
  84         if (genericInfo == null) {
  85             // create and cache generic info repository
  86             genericInfo =
  87                 ConstructorRepository.make(getSignature(),
  88                                            getFactory());
  89         }
  90         return genericInfo; //return cached repository
  91     }
  92 
  93     private volatile ConstructorAccessor constructorAccessor;
  94     // For sharing of ConstructorAccessors. This branching structure
  95     // is currently only two levels deep (i.e., one root Constructor
  96     // and potentially many Constructor objects pointing to it.)
  97     private Constructor<T>      root;
  98 
  99     /**
 100      * Package-private constructor used by ReflectAccess to enable
 101      * instantiation of these objects in Java code from the java.lang
 102      * package via sun.reflect.LangReflectAccess.
 103      */
 104     Constructor(Class<T> declaringClass,
 105                 Class<?>[] parameterTypes,
 106                 Class<?>[] checkedExceptions,
 107                 int modifiers,
 108                 int slot,
 109                 String signature,
 110                 byte[] annotations,
 111                 byte[] parameterAnnotations) {
 112         this.clazz = declaringClass;
 113         this.parameterTypes = parameterTypes;
 114         this.exceptionTypes = checkedExceptions;
 115         this.modifiers = modifiers;
 116         this.slot = slot;
 117         this.signature = signature;
 118         this.annotations = annotations;
 119         this.parameterAnnotations = parameterAnnotations;
 120     }
 121 
 122     /**
 123      * Package-private routine (exposed to java.lang.Class via
 124      * ReflectAccess) which returns a copy of this Constructor. The copy's
 125      * "root" field points to this Constructor.
 126      */
 127     Constructor<T> copy() {
 128         // This routine enables sharing of ConstructorAccessor objects
 129         // among Constructor objects which refer to the same underlying
 130         // method in the VM. (All of this contortion is only necessary
 131         // because of the "accessibility" bit in AccessibleObject,
 132         // which implicitly requires that new java.lang.reflect
 133         // objects be fabricated for each reflective call on Class
 134         // objects.)
 135         Constructor<T> res = new Constructor<>(clazz,
 136                                                parameterTypes,
 137                                                exceptionTypes, modifiers, slot,
 138                                                signature,
 139                                                annotations,
 140                                                parameterAnnotations);
 141         res.root = this;
 142         // Might as well eagerly propagate this if already present
 143         res.constructorAccessor = constructorAccessor;
 144         return res;
 145     }
 146 
 147     @Override
 148     boolean hasGenericInformation() {
 149         return (getSignature() != null);
 150     }
 151 
 152     @Override
 153     byte[] getAnnotationBytes() {
 154         return annotations;
 155     }
 156 
 157     /**
 158      * {@inheritDoc}
 159      */
 160     @Override
 161     public Class<T> getDeclaringClass() {
 162         return clazz;
 163     }
 164 
 165     /**
 166      * Returns the name of this constructor, as a string.  This is
 167      * the binary name of the constructor's declaring class.
 168      */
 169     @Override
 170     public String getName() {
 171         return getDeclaringClass().getName();
 172     }
 173 
 174     /**
 175      * {@inheritDoc}
 176      */
 177     @Override
 178     public int getModifiers() {
 179         return modifiers;
 180     }
 181 
 182     /**
 183      * {@inheritDoc}
 184      * @throws GenericSignatureFormatError {@inheritDoc}
 185      * @since 1.5
 186      */
 187     @Override
 188     @SuppressWarnings({"rawtypes", "unchecked"})
 189     public TypeVariable<Constructor<T>>[] getTypeParameters() {
 190       if (getSignature() != null) {
 191         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
 192       } else
 193           return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
 194     }
 195 
 196 
 197     /**
 198      * {@inheritDoc}
 199      */
 200     @Override
 201     public Class<?>[] getParameterTypes() {
 202         return parameterTypes.clone();
 203     }
 204 
 205     /**
 206      * {@inheritDoc}
 207      */
 208     public int getParameterCount() { return parameterTypes.length; }
 209 
 210     /**
 211      * {@inheritDoc}
 212      * @throws GenericSignatureFormatError {@inheritDoc}
 213      * @throws TypeNotPresentException {@inheritDoc}
 214      * @throws MalformedParameterizedTypeException {@inheritDoc}
 215      * @since 1.5
 216      */
 217     @Override
 218     public Type[] getGenericParameterTypes() {
 219         return super.getGenericParameterTypes();
 220     }
 221 
 222     /**
 223      * {@inheritDoc}
 224      */
 225     @Override
 226     public Class<?>[] getExceptionTypes() {
 227         return exceptionTypes.clone();
 228     }
 229 
 230 
 231     /**
 232      * {@inheritDoc}
 233      * @throws GenericSignatureFormatError {@inheritDoc}
 234      * @throws TypeNotPresentException {@inheritDoc}
 235      * @throws MalformedParameterizedTypeException {@inheritDoc}
 236      * @since 1.5
 237      */
 238     @Override
 239     public Type[] getGenericExceptionTypes() {
 240         return super.getGenericExceptionTypes();
 241     }
 242 
 243     /**
 244      * Compares this {@code Constructor} against the specified object.
 245      * Returns true if the objects are the same.  Two {@code Constructor} objects are
 246      * the same if they were declared by the same class and have the
 247      * same formal parameter types.
 248      */
 249     public boolean equals(Object obj) {
 250         if (obj != null && obj instanceof Constructor) {
 251             Constructor<?> other = (Constructor<?>)obj;
 252             if (getDeclaringClass() == other.getDeclaringClass()) {
 253                 return equalParamTypes(parameterTypes, other.parameterTypes);
 254             }
 255         }
 256         return false;
 257     }
 258 
 259     /**
 260      * Returns a hashcode for this {@code Constructor}. The hashcode is
 261      * the same as the hashcode for the underlying constructor's
 262      * declaring class name.
 263      */
 264     public int hashCode() {
 265         return getDeclaringClass().getName().hashCode();
 266     }
 267 
 268     /**
 269      * Returns a string describing this {@code Constructor}.  The string is
 270      * formatted as the constructor access modifiers, if any,
 271      * followed by the fully-qualified name of the declaring class,
 272      * followed by a parenthesized, comma-separated list of the
 273      * constructor's formal parameter types.  For example:
 274      * <pre>
 275      *    public java.util.Hashtable(int,float)
 276      * </pre>
 277      *
 278      * <p>The only possible modifiers for constructors are the access
 279      * modifiers {@code public}, {@code protected} or
 280      * {@code private}.  Only one of these may appear, or none if the
 281      * constructor has default (package) access.
 282      *
 283      * @return a string describing this {@code Constructor}
 284      * @jls 8.8.3. Constructor Modifiers
 285      */
 286     public String toString() {
 287         return sharedToString(Modifier.constructorModifiers(),
 288                               false,
 289                               parameterTypes,
 290                               exceptionTypes);
 291     }
 292 
 293     @Override
 294     void specificToStringHeader(StringBuilder sb) {
 295         sb.append(getDeclaringClass().getTypeName());
 296     }
 297 
 298     /**
 299      * Returns a string describing this {@code Constructor},
 300      * including type parameters.  The string is formatted as the
 301      * constructor access modifiers, if any, followed by an
 302      * angle-bracketed comma separated list of the constructor's type
 303      * parameters, if any, followed by the fully-qualified name of the
 304      * declaring class, followed by a parenthesized, comma-separated
 305      * list of the constructor's generic formal parameter types.
 306      *
 307      * If this constructor was declared to take a variable number of
 308      * arguments, instead of denoting the last parameter as
 309      * "<tt><i>Type</i>[]</tt>", it is denoted as
 310      * "<tt><i>Type</i>...</tt>".
 311      *
 312      * A space is used to separate access modifiers from one another
 313      * and from the type parameters or return type.  If there are no
 314      * type parameters, the type parameter list is elided; if the type
 315      * parameter list is present, a space separates the list from the
 316      * class name.  If the constructor is declared to throw
 317      * exceptions, the parameter list is followed by a space, followed
 318      * by the word "{@code throws}" followed by a
 319      * comma-separated list of the thrown exception types.
 320      *
 321      * <p>The only possible modifiers for constructors are the access
 322      * modifiers {@code public}, {@code protected} or
 323      * {@code private}.  Only one of these may appear, or none if the
 324      * constructor has default (package) access.
 325      *
 326      * @return a string describing this {@code Constructor},
 327      * include type parameters
 328      *
 329      * @since 1.5
 330      * @jls 8.8.3. Constructor Modifiers
 331      */
 332     @Override
 333     public String toGenericString() {
 334         return sharedToGenericString(Modifier.constructorModifiers(), false);
 335     }
 336 
 337     @Override
 338     void specificToGenericStringHeader(StringBuilder sb) {
 339         specificToStringHeader(sb);
 340     }
 341 
 342     /**
 343      * Uses the constructor represented by this {@code Constructor} object to
 344      * create and initialize a new instance of the constructor's
 345      * declaring class, with the specified initialization parameters.
 346      * Individual parameters are automatically unwrapped to match
 347      * primitive formal parameters, and both primitive and reference
 348      * parameters are subject to method invocation conversions as necessary.
 349      *
 350      * <p>If the number of formal parameters required by the underlying constructor
 351      * is 0, the supplied {@code initargs} array may be of length 0 or null.
 352      *
 353      * <p>If the constructor's declaring class is an inner class in a
 354      * non-static context, the first argument to the constructor needs
 355      * to be the enclosing instance; see section 15.9.3 of
 356      * <cite>The Java&trade; Language Specification</cite>.
 357      *
 358      * <p>If the required access and argument checks succeed and the
 359      * instantiation will proceed, the constructor's declaring class
 360      * is initialized if it has not already been initialized.
 361      *
 362      * <p>If the constructor completes normally, returns the newly
 363      * created and initialized instance.
 364      *
 365      * @param initargs array of objects to be passed as arguments to
 366      * the constructor call; values of primitive types are wrapped in
 367      * a wrapper object of the appropriate type (e.g. a {@code float}
 368      * in a {@link java.lang.Float Float})
 369      *
 370      * @return a new object created by calling the constructor
 371      * this object represents
 372      *
 373      * @exception IllegalAccessException    if this {@code Constructor} object
 374      *              is enforcing Java language access control and the underlying
 375      *              constructor is inaccessible.
 376      * @exception IllegalArgumentException  if the number of actual
 377      *              and formal parameters differ; if an unwrapping
 378      *              conversion for primitive arguments fails; or if,
 379      *              after possible unwrapping, a parameter value
 380      *              cannot be converted to the corresponding formal
 381      *              parameter type by a method invocation conversion; if
 382      *              this constructor pertains to an enum type.
 383      * @exception InstantiationException    if the class that declares the
 384      *              underlying constructor represents an abstract class.
 385      * @exception InvocationTargetException if the underlying constructor
 386      *              throws an exception.
 387      * @exception ExceptionInInitializerError if the initialization provoked
 388      *              by this method fails.
 389      */
 390     @CallerSensitive
 391     public T newInstance(Object ... initargs)
 392         throws InstantiationException, IllegalAccessException,
 393                IllegalArgumentException, InvocationTargetException
 394     {
 395         if (!override) {
 396             if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
 397                 Class<?> caller = Reflection.getCallerClass();
 398                 checkAccess(caller, clazz, null, modifiers);
 399             }
 400         }
 401         if ((clazz.getModifiers() & Modifier.ENUM) != 0)
 402             throw new IllegalArgumentException("Cannot reflectively create enum objects");
 403         ConstructorAccessor ca = constructorAccessor;   // read volatile
 404         if (ca == null) {
 405             ca = acquireConstructorAccessor();
 406         }
 407         @SuppressWarnings("unchecked")
 408         T inst = (T) ca.newInstance(initargs);
 409         return inst;
 410     }
 411 
 412     /**
 413      * {@inheritDoc}
 414      * @since 1.5
 415      */
 416     @Override
 417     public boolean isVarArgs() {
 418         return super.isVarArgs();
 419     }
 420 
 421     /**
 422      * {@inheritDoc}
 423      * @jls 13.1 The Form of a Binary
 424      * @since 1.5
 425      */
 426     @Override
 427     public boolean isSynthetic() {
 428         return super.isSynthetic();
 429     }
 430 
 431     // NOTE that there is no synchronization used here. It is correct
 432     // (though not efficient) to generate more than one
 433     // ConstructorAccessor for a given Constructor. However, avoiding
 434     // synchronization will probably make the implementation more
 435     // scalable.
 436     private ConstructorAccessor acquireConstructorAccessor() {
 437         // First check to see if one has been created yet, and take it
 438         // if so.
 439         ConstructorAccessor tmp = null;
 440         if (root != null) tmp = root.getConstructorAccessor();
 441         if (tmp != null) {
 442             constructorAccessor = tmp;
 443         } else {
 444             // Otherwise fabricate one and propagate it up to the root
 445             tmp = reflectionFactory.newConstructorAccessor(this);
 446             setConstructorAccessor(tmp);
 447         }
 448 
 449         return tmp;
 450     }
 451 
 452     // Returns ConstructorAccessor for this Constructor object, not
 453     // looking up the chain to the root
 454     ConstructorAccessor getConstructorAccessor() {
 455         return constructorAccessor;
 456     }
 457 
 458     // Sets the ConstructorAccessor for this Constructor object and
 459     // (recursively) its root
 460     void setConstructorAccessor(ConstructorAccessor accessor) {
 461         constructorAccessor = accessor;
 462         // Propagate up
 463         if (root != null) {
 464             root.setConstructorAccessor(accessor);
 465         }
 466     }
 467 
 468     int getSlot() {
 469         return slot;
 470     }
 471 
 472     String getSignature() {
 473         return signature;
 474     }
 475 
 476     byte[] getRawAnnotations() {
 477         return annotations;
 478     }
 479 
 480     byte[] getRawParameterAnnotations() {
 481         return parameterAnnotations;
 482     }
 483 
 484 
 485     /**
 486      * {@inheritDoc}
 487      * @throws NullPointerException  {@inheritDoc}
 488      * @since 1.5
 489      */
 490     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 491         return super.getAnnotation(annotationClass);
 492     }
 493 
 494     /**
 495      * {@inheritDoc}
 496      * @since 1.5
 497      */
 498     public Annotation[] getDeclaredAnnotations()  {
 499         return super.getDeclaredAnnotations();
 500     }
 501 
 502     /**
 503      * {@inheritDoc}
 504      * @since 1.5
 505      */
 506     @Override
 507     public Annotation[][] getParameterAnnotations() {
 508         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
 509     }
 510 
 511     @Override
 512     void handleParameterNumberMismatch(int resultLength, int numParameters) {
 513         Class<?> declaringClass = getDeclaringClass();
 514         if (declaringClass.isEnum() ||
 515             declaringClass.isAnonymousClass() ||
 516             declaringClass.isLocalClass() )
 517             return ; // Can't do reliable parameter counting
 518         else {
 519             if (!declaringClass.isMemberClass() || // top-level
 520                 // Check for the enclosing instance parameter for
 521                 // non-static member classes
 522                 (declaringClass.isMemberClass() &&
 523                  ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
 524                  resultLength + 1 != numParameters) ) {
 525                 throw new AnnotationFormatError(
 526                           "Parameter annotations don't match number of parameters");
 527             }
 528         }
 529     }
 530 
 531     /**
 532      * {@inheritDoc}
 533      * @since 1.8
 534      */
 535     @Override
 536     public AnnotatedType getAnnotatedReturnType() {
 537         return getAnnotatedReturnType0(getDeclaringClass());
 538     }
 539 
 540     /**
 541      * {@inheritDoc}
 542      * @since 1.8
 543      */
 544     @Override
 545     public AnnotatedType getAnnotatedReceiverType() {
 546         Class<?> thisDeclClass = getDeclaringClass();
 547         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
 548 
 549         if (enclosingClass == null) {
 550             // A Constructor for a top-level class
 551             return null;
 552         }
 553 
 554         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
 555         if (outerDeclaringClass == null) {
 556             // A constructor for a local or anonymous class
 557             return null;
 558         }
 559 
 560         // Either static nested or inner class
 561         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
 562             // static nested
 563             return null;
 564         }
 565 
 566         // A Constructor for an inner class
 567         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
 568                 sun.misc.SharedSecrets.getJavaLangAccess().
 569                     getConstantPool(thisDeclClass),
 570                 this,
 571                 thisDeclClass,
 572                 enclosingClass,
 573                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
 574     }
 575 }