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