1 /*
  2  * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.reflect;
 27 
 28 import jdk.internal.access.SharedSecrets;
 29 import jdk.internal.value.PrimitiveClass;
 30 import jdk.internal.misc.VM;
 31 import jdk.internal.reflect.CallerSensitive;
 32 import jdk.internal.reflect.ConstructorAccessor;
 33 import jdk.internal.reflect.Reflection;
 34 import jdk.internal.vm.annotation.ForceInline;
 35 import jdk.internal.vm.annotation.Stable;
 36 import sun.reflect.annotation.TypeAnnotation;
 37 import sun.reflect.annotation.TypeAnnotationParser;
 38 import sun.reflect.generics.repository.ConstructorRepository;
 39 import sun.reflect.generics.repository.GenericDeclRepository;
 40 import sun.reflect.generics.factory.CoreReflectionFactory;
 41 import sun.reflect.generics.factory.GenericsFactory;
 42 import sun.reflect.generics.scope.ConstructorScope;
 43 import java.lang.annotation.Annotation;
 44 import java.lang.annotation.AnnotationFormatError;
 45 import java.util.StringJoiner;
 46 
 47 /**
 48  * {@code Constructor} provides information about, and access to, a single
 49  * constructor for a class.
 50  *
 51  * <p>{@code Constructor} permits widening conversions to occur when matching the
 52  * actual parameters to newInstance() with the underlying
 53  * constructor's formal parameters, but throws an
 54  * {@code IllegalArgumentException} if a narrowing conversion would occur.
 55  *
 56  * @param <T> the class in which the constructor is declared
 57  *
 58  * @see Member
 59  * @see java.lang.Class
 60  * @see java.lang.Class#getConstructors()
 61  * @see java.lang.Class#getConstructor(Class[])
 62  * @see java.lang.Class#getDeclaredConstructors()
 63  *
 64  * @author      Kenneth Russell
 65  * @author      Nakul Saraiya
 66  * @since 1.1
 67  */
 68 public final class Constructor<T> extends Executable {
 69     private final Class<T>            clazz;
 70     private final int                 slot;
 71     private final Class<?>[]          parameterTypes;
 72     private final Class<?>[]          exceptionTypes;
 73     private final int                 modifiers;
 74     // Generics and annotations support
 75     private final transient String    signature;
 76     // generic info repository; lazily initialized
 77     private transient ConstructorRepository genericInfo;
 78     private final byte[]              annotations;
 79     private final byte[]              parameterAnnotations;
 80 
 81     // Generics infrastructure
 82     // Accessor for factory
 83     private GenericsFactory getFactory() {
 84         // create scope and factory
 85         return CoreReflectionFactory.make(this, ConstructorScope.make(this));
 86     }
 87 
 88     // Accessor for generic info repository
 89     @Override
 90     ConstructorRepository getGenericInfo() {
 91         // lazily initialize repository if necessary
 92         if (genericInfo == null) {
 93             // create and cache generic info repository
 94             genericInfo =
 95                 ConstructorRepository.make(getSignature(),
 96                                            getFactory());
 97         }
 98         return genericInfo; //return cached repository
 99     }
100 
101     @Stable
102     private ConstructorAccessor constructorAccessor;
103     // For sharing of ConstructorAccessors. This branching structure
104     // is currently only two levels deep (i.e., one root Constructor
105     // and potentially many Constructor objects pointing to it.)
106     //
107     // If this branching structure would ever contain cycles, deadlocks can
108     // occur in annotation code.
109     private Constructor<T>      root;
110 
111     @Override
112     Constructor<T> getRoot() {
113         return root;
114     }
115 
116     /**
117      * Package-private constructor used by ReflectAccess to enable
118      * instantiation of these objects in Java code from the java.lang
119      * package via jdk.internal.access.JavaLangReflectAccess.
120      */
121     Constructor(Class<T> declaringClass,
122                 Class<?>[] parameterTypes,
123                 Class<?>[] checkedExceptions,
124                 int modifiers,
125                 int slot,
126                 String signature,
127                 byte[] annotations,
128                 byte[] parameterAnnotations) {
129         assert PrimitiveClass.isPrimaryType(declaringClass);
130         this.clazz = declaringClass;
131         this.parameterTypes = parameterTypes;
132         this.exceptionTypes = checkedExceptions;
133         this.modifiers = modifiers;
134         this.slot = slot;
135         this.signature = signature;
136         this.annotations = annotations;
137         this.parameterAnnotations = parameterAnnotations;
138     }
139 
140     /**
141      * Package-private routine (exposed to java.lang.Class via
142      * ReflectAccess) which returns a copy of this Constructor. The copy's
143      * "root" field points to this Constructor.
144      */
145     Constructor<T> copy() {
146         // This routine enables sharing of ConstructorAccessor objects
147         // among Constructor objects which refer to the same underlying
148         // method in the VM. (All of this contortion is only necessary
149         // because of the "accessibility" bit in AccessibleObject,
150         // which implicitly requires that new java.lang.reflect
151         // objects be fabricated for each reflective call on Class
152         // objects.)
153         if (this.root != null)
154             throw new IllegalArgumentException("Can not copy a non-root Constructor");
155 
156         Constructor<T> res = new Constructor<>(clazz,
157                                                parameterTypes,
158                                                exceptionTypes, modifiers, slot,
159                                                signature,
160                                                annotations,
161                                                parameterAnnotations);
162         res.root = this;
163         // Might as well eagerly propagate this if already present
164         res.constructorAccessor = constructorAccessor;
165         return res;
166     }
167 
168     /**
169      * {@inheritDoc}
170      *
171      * <p> A {@code SecurityException} is also thrown if this object is a
172      * {@code Constructor} object for the class {@code Class} and {@code flag}
173      * is true. </p>
174      *
175      * @param flag {@inheritDoc}
176      *
177      * @throws InaccessibleObjectException {@inheritDoc}
178      * @throws SecurityException if the request is denied by the security manager
179      *         or this is a constructor for {@code java.lang.Class}
180      *
181      */
182     @Override
183     @CallerSensitive
184     public void setAccessible(boolean flag) {
185         AccessibleObject.checkPermission();
186         if (flag) {
187             checkCanSetAccessible(Reflection.getCallerClass());
188         }
189         setAccessible0(flag);
190     }
191 
192     @Override
193     void checkCanSetAccessible(Class<?> caller) {
194         checkCanSetAccessible(caller, clazz);
195         if (clazz == Class.class) {
196             // can we change this to InaccessibleObjectException?
197             throw new SecurityException("Cannot make a java.lang.Class"
198                                         + " constructor accessible");
199         }
200     }
201 
202     @Override
203     boolean hasGenericInformation() {
204         return (getSignature() != null);
205     }
206 
207     @Override
208     byte[] getAnnotationBytes() {
209         return annotations;
210     }
211 
212     /**
213      * Returns the {@code Class} object representing the class that
214      * declares the constructor represented by this object.
215      */
216     @Override
217     public Class<T> getDeclaringClass() {
218         return clazz;
219     }
220 
221     /**
222      * Returns the name of this constructor, as a string.  This is
223      * the binary name of the constructor's declaring class.
224      */
225     @Override
226     public String getName() {
227         return getDeclaringClass().getName();
228     }
229 
230     /**
231      * {@inheritDoc}
232      * @jls 8.8.3 Constructor Modifiers
233      */
234     @Override
235     public int getModifiers() {
236         return modifiers;
237     }
238 
239     /**
240      * {@inheritDoc}
241      * @throws GenericSignatureFormatError {@inheritDoc}
242      * @since 1.5
243      */
244     @Override
245     @SuppressWarnings({"rawtypes", "unchecked"})
246     public TypeVariable<Constructor<T>>[] getTypeParameters() {
247       if (getSignature() != null) {
248         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
249       } else
250           return (TypeVariable<Constructor<T>>[])GenericDeclRepository.EMPTY_TYPE_VARS;
251     }
252 
253 
254     @Override
255     Class<?>[] getSharedParameterTypes() {
256         return parameterTypes;
257     }
258 
259     @Override
260     Class<?>[] getSharedExceptionTypes() {
261         return exceptionTypes;
262     }
263 
264     /**
265      * {@inheritDoc}
266      */
267     @Override
268     public Class<?>[] getParameterTypes() {
269         return parameterTypes.clone();
270     }
271 
272     /**
273      * {@inheritDoc}
274      * @since 1.8
275      */
276     public int getParameterCount() { return parameterTypes.length; }
277 
278     /**
279      * {@inheritDoc}
280      * @throws GenericSignatureFormatError {@inheritDoc}
281      * @throws TypeNotPresentException {@inheritDoc}
282      * @throws MalformedParameterizedTypeException {@inheritDoc}
283      * @since 1.5
284      */
285     @Override
286     public Type[] getGenericParameterTypes() {
287         return super.getGenericParameterTypes();
288     }
289 
290     /**
291      * {@inheritDoc}
292      */
293     @Override
294     public Class<?>[] getExceptionTypes() {
295         return exceptionTypes.clone();
296     }
297 
298 
299     /**
300      * {@inheritDoc}
301      * @throws GenericSignatureFormatError {@inheritDoc}
302      * @throws TypeNotPresentException {@inheritDoc}
303      * @throws MalformedParameterizedTypeException {@inheritDoc}
304      * @since 1.5
305      */
306     @Override
307     public Type[] getGenericExceptionTypes() {
308         return super.getGenericExceptionTypes();
309     }
310 
311     /**
312      * Compares this {@code Constructor} against the specified object.
313      * Returns true if the objects are the same.  Two {@code Constructor} objects are
314      * the same if they were declared by the same class and have the
315      * same formal parameter types.
316      */
317     public boolean equals(Object obj) {
318         if (obj instanceof Constructor<?> other) {
319             if (getDeclaringClass() == other.getDeclaringClass()) {
320                 return equalParamTypes(parameterTypes, other.parameterTypes);
321             }
322         }
323         return false;
324     }
325 
326     /**
327      * Returns a hashcode for this {@code Constructor}. The hashcode is
328      * the same as the hashcode for the underlying constructor's
329      * declaring class name.
330      */
331     public int hashCode() {
332         return getDeclaringClass().getName().hashCode();
333     }
334 
335     /**
336      * Returns a string describing this {@code Constructor}.  The string is
337      * formatted as the constructor access modifiers, if any,
338      * followed by the fully-qualified name of the declaring class,
339      * followed by a parenthesized, comma-separated list of the
340      * constructor's formal parameter types.  For example:
341      * <pre>{@code
342      *    public java.util.HashMap(int,float)
343      * }</pre>
344      *
345      * <p>If the constructor is declared to throw exceptions, the
346      * parameter list is followed by a space, followed by the word
347      * "{@code throws}" followed by a comma-separated list of the
348      * thrown exception types.
349      *
350      * <p>The only possible modifiers for constructors are the access
351      * modifiers {@code public}, {@code protected} or
352      * {@code private}.  Only one of these may appear, or none if the
353      * constructor has default (package) access.
354      *
355      * @return a string describing this {@code Constructor}
356      * @jls 8.8.3 Constructor Modifiers
357      * @jls 8.9.2 Enum Body Declarations
358      */
359     public String toString() {
360         return sharedToString(Modifier.constructorModifiers(),
361                               false,
362                               parameterTypes,
363                               exceptionTypes);
364     }
365 
366     @Override
367     void specificToStringHeader(StringBuilder sb) {
368         sb.append(getDeclaringClassTypeName());
369     }
370 
371     @Override
372     String toShortString() {
373         StringBuilder sb = new StringBuilder("constructor ");
374         sb.append(getDeclaringClassTypeName());
375         sb.append('(');
376         StringJoiner sj = new StringJoiner(",");
377         for (Class<?> parameterType : getSharedParameterTypes()) {
378             sj.add(parameterType.getTypeName());
379         }
380         sb.append(sj);
381         sb.append(')');
382         return sb.toString();
383     }
384 
385     /**
386      * Returns a string describing this {@code Constructor},
387      * including type parameters.  The string is formatted as the
388      * constructor access modifiers, if any, followed by an
389      * angle-bracketed comma separated list of the constructor's type
390      * parameters, if any, including  informative bounds of the
391      * type parameters, if any, followed by the fully-qualified name of the
392      * declaring class, followed by a parenthesized, comma-separated
393      * list of the constructor's generic formal parameter types.
394      *
395      * If this constructor was declared to take a variable number of
396      * arguments, instead of denoting the last parameter as
397      * "<code><i>Type</i>[]</code>", it is denoted as
398      * "<code><i>Type</i>...</code>".
399      *
400      * A space is used to separate access modifiers from one another
401      * and from the type parameters or class name.  If there are no
402      * type parameters, the type parameter list is elided; if the type
403      * parameter list is present, a space separates the list from the
404      * class name.  If the constructor is declared to throw
405      * exceptions, the parameter list is followed by a space, followed
406      * by the word "{@code throws}" followed by a
407      * comma-separated list of the generic thrown exception types.
408      *
409      * <p>The only possible modifiers for constructors are the access
410      * modifiers {@code public}, {@code protected} or
411      * {@code private}.  Only one of these may appear, or none if the
412      * constructor has default (package) access.
413      *
414      * @return a string describing this {@code Constructor},
415      * include type parameters
416      *
417      * @since 1.5
418      * @jls 8.8.3 Constructor Modifiers
419      * @jls 8.9.2 Enum Body Declarations
420      */
421     @Override
422     public String toGenericString() {
423         return sharedToGenericString(Modifier.constructorModifiers(), false);
424     }
425 
426     @Override
427     void specificToGenericStringHeader(StringBuilder sb) {
428         specificToStringHeader(sb);
429     }
430 
431     /**
432      * Uses the constructor represented by this {@code Constructor} object to
433      * create and initialize a new instance of the constructor's
434      * declaring class, with the specified initialization parameters.
435      * Individual parameters are automatically unwrapped to match
436      * primitive formal parameters, and both primitive and reference
437      * parameters are subject to method invocation conversions as necessary.
438      *
439      * <p>If the number of formal parameters required by the underlying constructor
440      * is 0, the supplied {@code initargs} array may be of length 0 or null.
441      *
442      * <p>If the constructor's declaring class is an inner class in a
443      * non-static context, the first argument to the constructor needs
444      * to be the enclosing instance; see section {@jls 15.9.3} of
445      * <cite>The Java Language Specification</cite>.
446      *
447      * <p>If the required access and argument checks succeed and the
448      * instantiation will proceed, the constructor's declaring class
449      * is initialized if it has not already been initialized.
450      *
451      * <p>If the constructor completes normally, returns the newly
452      * created and initialized instance.
453      *
454      * @param initargs array of objects to be passed as arguments to
455      * the constructor call; values of primitive types are wrapped in
456      * a wrapper object of the appropriate type (e.g. a {@code float}
457      * in a {@link java.lang.Float Float})
458      *
459      * @return a new object created by calling the constructor
460      * this object represents
461      *
462      * @throws    IllegalAccessException    if this {@code Constructor} object
463      *              is enforcing Java language access control and the underlying
464      *              constructor is inaccessible.
465      * @throws    IllegalArgumentException  if the number of actual
466      *              and formal parameters differ; if an unwrapping
467      *              conversion for primitive arguments fails; or if,
468      *              after possible unwrapping, a parameter value
469      *              cannot be converted to the corresponding formal
470      *              parameter type by a method invocation conversion; if
471      *              this constructor pertains to an enum class.
472      * @throws    InstantiationException    if the class that declares the
473      *              underlying constructor represents an abstract class.
474      * @throws    InvocationTargetException if the underlying constructor
475      *              throws an exception.
476      * @throws    ExceptionInInitializerError if the initialization provoked
477      *              by this method fails.
478      */
479     @CallerSensitive
480     @ForceInline // to ensure Reflection.getCallerClass optimization
481     public T newInstance(Object ... initargs)
482         throws InstantiationException, IllegalAccessException,
483                IllegalArgumentException, InvocationTargetException
484     {
485         Class<?> caller = override ? null : Reflection.getCallerClass();
486         return newInstanceWithCaller(initargs, !override, caller);
487     }
488 
489     /* package-private */
490     T newInstanceWithCaller(Object[] args, boolean checkAccess, Class<?> caller)
491         throws InstantiationException, IllegalAccessException,
492                InvocationTargetException
493     {
494         if (checkAccess)
495             checkAccess(caller, clazz, clazz, modifiers);
496 
497         ConstructorAccessor ca = constructorAccessor;   // read @Stable
498         if (ca == null) {
499             ca = acquireConstructorAccessor();
500         }
501         @SuppressWarnings("unchecked")
502         T inst = (T) ca.newInstance(args);
503         return inst;
504     }
505 
506     /**
507      * {@inheritDoc}
508      * @since 1.5
509      * @jls 8.4.1 Formal Parameters
510      */
511     @Override
512     public boolean isVarArgs() {
513         return super.isVarArgs();
514     }
515 
516     /**
517      * {@inheritDoc}
518      * @jls 13.1 The Form of a Binary
519      * @jvms 4.6 Methods
520      * @since 1.5
521      * @see <a
522      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
523      * programming language and JVM modeling in core reflection</a>
524      */
525     @Override
526     public boolean isSynthetic() {
527         return super.isSynthetic();
528     }
529 
530     // NOTE that there is no synchronization used here. It is correct
531     // (though not efficient) to generate more than one
532     // ConstructorAccessor for a given Constructor. However, avoiding
533     // synchronization will probably make the implementation more
534     // scalable.
535     private ConstructorAccessor acquireConstructorAccessor() {
536 
537         // First check to see if one has been created yet, and take it
538         // if so.
539         Constructor<?> root = this.root;
540         ConstructorAccessor tmp = root == null ? null : root.getConstructorAccessor();
541         if (tmp != null) {
542             constructorAccessor = tmp;
543         } else {
544             // Otherwise fabricate one and propagate it up to the root
545             // Ensure the declaring class is not an Enum class.
546             if ((clazz.getModifiers() & Modifier.ENUM) != 0)
547                 throw new IllegalArgumentException("Cannot reflectively create enum objects");
548 
549             tmp = reflectionFactory.newConstructorAccessor(this);
550             // set the constructor accessor only if it's not using native implementation
551             if (VM.isJavaLangInvokeInited())
552                 setConstructorAccessor(tmp);
553         }
554 
555         return tmp;
556     }
557 
558     // Returns ConstructorAccessor for this Constructor object, not
559     // looking up the chain to the root
560     ConstructorAccessor getConstructorAccessor() {
561         return constructorAccessor;
562     }
563 
564     // Sets the ConstructorAccessor for this Constructor object and
565     // (recursively) its root
566     void setConstructorAccessor(ConstructorAccessor accessor) {
567         constructorAccessor = accessor;
568         // Propagate up
569         Constructor<?> root = this.root;
570         if (root != null) {
571             root.setConstructorAccessor(accessor);
572         }
573     }
574 
575     int getSlot() {
576         return slot;
577     }
578 
579     String getSignature() {
580         return signature;
581     }
582 
583     byte[] getRawAnnotations() {
584         return annotations;
585     }
586 
587     byte[] getRawParameterAnnotations() {
588         return parameterAnnotations;
589     }
590 
591 
592     /**
593      * {@inheritDoc}
594      *
595      * @throws NullPointerException  {@inheritDoc}
596      * @since 1.5
597      */
598     @Override
599     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
600         return super.getAnnotation(annotationClass);
601     }
602 
603     /**
604      * {@inheritDoc}
605      * @since 1.5
606      */
607     @Override
608     public Annotation[] getDeclaredAnnotations()  {
609         return super.getDeclaredAnnotations();
610     }
611 
612     /**
613      * {@inheritDoc}
614      * @since 1.5
615      */
616     @Override
617     public Annotation[][] getParameterAnnotations() {
618         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
619     }
620 
621     @Override
622     boolean handleParameterNumberMismatch(int resultLength, Class<?>[] parameterTypes) {
623         int numParameters = parameterTypes.length;
624         Class<?> declaringClass = getDeclaringClass();
625         if (declaringClass.isEnum()) {
626             return resultLength + 2 == numParameters &&
627                     parameterTypes[0] == String.class &&
628                     parameterTypes[1] == int.class;
629         } else if (
630             declaringClass.isAnonymousClass() ||
631             declaringClass.isLocalClass() )
632             return false; // Can't do reliable parameter counting
633         else {
634             if (declaringClass.isMemberClass() &&
635                 ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
636                 resultLength + 1 == numParameters) {
637                 return true;
638             } else {
639                 throw new AnnotationFormatError(
640                           "Parameter annotations don't match number of parameters");
641             }
642         }
643     }
644 
645     /**
646      * {@inheritDoc}
647      * @since 1.8
648      */
649     @Override
650     public AnnotatedType getAnnotatedReturnType() {
651         return getAnnotatedReturnType0(getDeclaringClass());
652     }
653 
654     /**
655      * {@inheritDoc}
656      * @since 1.8
657      */
658     @Override
659     public AnnotatedType getAnnotatedReceiverType() {
660         Class<?> thisDeclClass = getDeclaringClass();
661         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
662 
663         if (enclosingClass == null) {
664             // A Constructor for a top-level class
665             return null;
666         }
667 
668         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
669         if (outerDeclaringClass == null) {
670             // A constructor for a local or anonymous class
671             return null;
672         }
673 
674         // Either static nested or inner class
675         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
676             // static nested
677             return null;
678         }
679 
680         // A Constructor for an inner class
681         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
682                 SharedSecrets.getJavaLangAccess().
683                     getConstantPool(thisDeclClass),
684                 this,
685                 thisDeclClass,
686                 parameterize(enclosingClass),
687                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
688     }
689 }