1 /*
  2  * Copyright (c) 1996, 2021, 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.misc.VM;
 30 import jdk.internal.reflect.CallerSensitive;
 31 import jdk.internal.reflect.ConstructorAccessor;
 32 import jdk.internal.reflect.Reflection;
 33 import jdk.internal.vm.annotation.ForceInline;
 34 import jdk.internal.vm.annotation.Stable;
 35 import sun.reflect.annotation.TypeAnnotation;
 36 import sun.reflect.annotation.TypeAnnotationParser;
 37 import sun.reflect.generics.repository.ConstructorRepository;
 38 import sun.reflect.generics.factory.CoreReflectionFactory;
 39 import sun.reflect.generics.factory.GenericsFactory;
 40 import sun.reflect.generics.scope.ConstructorScope;
 41 import java.lang.annotation.Annotation;
 42 import java.lang.annotation.AnnotationFormatError;
 43 import java.util.StringJoiner;
 44 
 45 /**
 46  * {@code Constructor} provides information about, and access to, a single
 47  * constructor for a class.
 48  *
 49  * <p>{@code Constructor} permits widening conversions to occur when matching the
 50  * actual parameters to newInstance() with the underlying
 51  * constructor's formal parameters, but throws an
 52  * {@code IllegalArgumentException} if a narrowing conversion would occur.
 53  *
 54  * @param <T> the class in which the constructor is declared
 55  *
 56  * @see Member
 57  * @see java.lang.Class
 58  * @see java.lang.Class#getConstructors()
 59  * @see java.lang.Class#getConstructor(Class[])
 60  * @see java.lang.Class#getDeclaredConstructors()
 61  *
 62  * @author      Kenneth Russell
 63  * @author      Nakul Saraiya
 64  * @since 1.1
 65  */
 66 public final class Constructor<T> extends Executable {
 67     private final Class<T>            clazz;
 68     private final int                 slot;
 69     private final Class<?>[]          parameterTypes;
 70     private final Class<?>[]          exceptionTypes;
 71     private final int                 modifiers;
 72     // Generics and annotations support
 73     private final transient String    signature;
 74     // generic info repository; lazily initialized
 75     private transient ConstructorRepository genericInfo;
 76     private final byte[]              annotations;
 77     private final byte[]              parameterAnnotations;
 78 
 79     // Generics infrastructure
 80     // Accessor for factory
 81     private GenericsFactory getFactory() {
 82         // create scope and factory
 83         return CoreReflectionFactory.make(this, ConstructorScope.make(this));
 84     }
 85 
 86     // Accessor for generic info repository
 87     @Override
 88     ConstructorRepository getGenericInfo() {
 89         // lazily initialize repository if necessary
 90         if (genericInfo == null) {
 91             // create and cache generic info repository
 92             genericInfo =
 93                 ConstructorRepository.make(getSignature(),
 94                                            getFactory());
 95         }
 96         return genericInfo; //return cached repository
 97     }
 98 
 99     @Stable
100     private ConstructorAccessor constructorAccessor;
101     // For sharing of ConstructorAccessors. This branching structure
102     // is currently only two levels deep (i.e., one root Constructor
103     // and potentially many Constructor objects pointing to it.)
104     //
105     // If this branching structure would ever contain cycles, deadlocks can
106     // occur in annotation code.
107     private Constructor<T>      root;
108 
109     @Override
110     Constructor<T> 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 jdk.internal.access.JavaLangReflectAccess.
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      */
179     @Override
180     @CallerSensitive
181     public void setAccessible(boolean flag) {
182         AccessibleObject.checkPermission();
183         if (flag) {
184             checkCanSetAccessible(Reflection.getCallerClass());
185         }
186         setAccessible0(flag);
187     }
188 
189     @Override
190     void checkCanSetAccessible(Class<?> caller) {
191         checkCanSetAccessible(caller, clazz);
192         if (clazz == Class.class) {
193             // can we change this to InaccessibleObjectException?
194             throw new SecurityException("Cannot make a java.lang.Class"
195                                         + " constructor accessible");
196         }
197     }
198 
199     @Override
200     boolean hasGenericInformation() {
201         return (getSignature() != null);
202     }
203 
204     @Override
205     byte[] getAnnotationBytes() {
206         return annotations;
207     }
208 
209     /**
210      * Returns the {@code Class} object representing the class that
211      * declares the constructor represented by this object.
212      */
213     @Override
214     public Class<T> getDeclaringClass() {
215         return clazz;
216     }
217 
218     /**
219      * Returns the name of this constructor, as a string.  This is
220      * the binary name of the constructor's declaring class.
221      */
222     @Override
223     public String getName() {
224         return getDeclaringClass().getName();
225     }
226 
227     /**
228      * {@inheritDoc}
229      * @jls 8.8.3 Constructor Modifiers
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 instanceof Constructor<?> other) {
316             if (getDeclaringClass() == other.getDeclaringClass()) {
317                 return equalParamTypes(parameterTypes, other.parameterTypes);
318             }
319         }
320         return false;
321     }
322 
323     /**
324      * Returns a hashcode for this {@code Constructor}. The hashcode is
325      * the same as the hashcode for the underlying constructor's
326      * declaring class name.
327      */
328     public int hashCode() {
329         return getDeclaringClass().getName().hashCode();
330     }
331 
332     /**
333      * Returns a string describing this {@code Constructor}.  The string is
334      * formatted as the constructor access modifiers, if any,
335      * followed by the fully-qualified name of the declaring class,
336      * followed by a parenthesized, comma-separated list of the
337      * constructor's formal parameter types.  For example:
338      * <pre>{@code
339      *    public java.util.HashMap(int,float)
340      * }</pre>
341      *
342      * <p>If the constructor is declared to throw exceptions, the
343      * parameter list is followed by a space, followed by the word
344      * "{@code throws}" followed by a comma-separated list of the
345      * thrown exception types.
346      *
347      * <p>The only possible modifiers for constructors are the access
348      * modifiers {@code public}, {@code protected} or
349      * {@code private}.  Only one of these may appear, or none if the
350      * constructor has default (package) access.
351      *
352      * @return a string describing this {@code Constructor}
353      * @jls 8.8.3 Constructor Modifiers
354      * @jls 8.9.2 Enum Body Declarations
355      */
356     public String toString() {
357         return sharedToString(Modifier.constructorModifiers(),
358                               false,
359                               parameterTypes,
360                               exceptionTypes);
361     }
362 
363     @Override
364     void specificToStringHeader(StringBuilder sb) {
365         sb.append(getDeclaringClass().getTypeName());
366     }
367 
368     @Override
369     String toShortString() {
370         StringBuilder sb = new StringBuilder("constructor ");
371         sb.append(getDeclaringClass().getTypeName());
372         sb.append('(');
373         StringJoiner sj = new StringJoiner(",");
374         for (Class<?> parameterType : getSharedParameterTypes()) {
375             sj.add(parameterType.getTypeName());
376         }
377         sb.append(sj);
378         sb.append(')');
379         return sb.toString();
380     }
381 
382     /**
383      * Returns a string describing this {@code Constructor},
384      * including type parameters.  The string is formatted as the
385      * constructor access modifiers, if any, followed by an
386      * angle-bracketed comma separated list of the constructor's type
387      * parameters, if any, including  informative bounds of the
388      * type 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 {@jls 15.9.3} of
442      * <cite>The Java 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      * @throws    IllegalAccessException    if this {@code Constructor} object
460      *              is enforcing Java language access control and the underlying
461      *              constructor is inaccessible.
462      * @throws    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 class.
469      * @throws    InstantiationException    if the class that declares the
470      *              underlying constructor represents an abstract class.
471      * @throws    InvocationTargetException if the underlying constructor
472      *              throws an exception.
473      * @throws    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         Class<?> caller = override ? null : Reflection.getCallerClass();
483         return newInstanceWithCaller(initargs, !override, caller);
484     }
485 
486     /* package-private */
487     T newInstanceWithCaller(Object[] args, boolean checkAccess, Class<?> caller)
488         throws InstantiationException, IllegalAccessException,
489                InvocationTargetException
490     {
491         if (checkAccess)
492             checkAccess(caller, clazz, clazz, modifiers);
493 
494         ConstructorAccessor ca = constructorAccessor;   // read @Stable
495         if (ca == null) {
496             ca = acquireConstructorAccessor();
497         }
498         @SuppressWarnings("unchecked")
499         T inst = (T) ca.newInstance(args);
500         return inst;
501     }
502 
503     /**
504      * {@inheritDoc}
505      * @since 1.5
506      * @jls 8.4.1 Formal Parameters
507      */
508     @Override
509     public boolean isVarArgs() {
510         return super.isVarArgs();
511     }
512 
513     /**
514      * {@inheritDoc}
515      * @jls 13.1 The Form of a Binary
516      * @jvms 4.6 Methods
517      * @since 1.5
518      * @see <a
519      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
520      * programming language and JVM modeling in core reflection</a>
521      */
522     @Override
523     public boolean isSynthetic() {
524         return super.isSynthetic();
525     }
526 
527     // NOTE that there is no synchronization used here. It is correct
528     // (though not efficient) to generate more than one
529     // ConstructorAccessor for a given Constructor. However, avoiding
530     // synchronization will probably make the implementation more
531     // scalable.
532     private ConstructorAccessor acquireConstructorAccessor() {
533 
534         // First check to see if one has been created yet, and take it
535         // if so.
536         Constructor<?> root = this.root;
537         ConstructorAccessor tmp = root == null ? null : root.getConstructorAccessor();
538         if (tmp != null) {
539             constructorAccessor = tmp;
540         } else {
541             // Otherwise fabricate one and propagate it up to the root
542             // Ensure the declaring class is not an Enum class.
543             if ((clazz.getModifiers() & Modifier.ENUM) != 0)
544                 throw new IllegalArgumentException("Cannot reflectively create enum objects");
545 
546             tmp = reflectionFactory.newConstructorAccessor(this);
547             // set the constructor accessor only if it's not using native implementation
548             if (VM.isJavaLangInvokeInited())
549                 setConstructorAccessor(tmp);
550         }
551 
552         return tmp;
553     }
554 
555     // Returns ConstructorAccessor for this Constructor object, not
556     // looking up the chain to the root
557     ConstructorAccessor getConstructorAccessor() {
558         return constructorAccessor;
559     }
560 
561     // Sets the ConstructorAccessor for this Constructor object and
562     // (recursively) its root
563     void setConstructorAccessor(ConstructorAccessor accessor) {
564         constructorAccessor = accessor;
565         // Propagate up
566         Constructor<?> root = this.root;
567         if (root != null) {
568             root.setConstructorAccessor(accessor);
569         }
570     }
571 
572     int getSlot() {
573         return slot;
574     }
575 
576     String getSignature() {
577         return signature;
578     }
579 
580     byte[] getRawAnnotations() {
581         return annotations;
582     }
583 
584     byte[] getRawParameterAnnotations() {
585         return parameterAnnotations;
586     }
587 
588 
589     /**
590      * {@inheritDoc}
591      *
592      * @throws NullPointerException  {@inheritDoc}
593      * @since 1.5
594      */
595     @Override
596     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
597         return super.getAnnotation(annotationClass);
598     }
599 
600     /**
601      * {@inheritDoc}
602      * @since 1.5
603      */
604     @Override
605     public Annotation[] getDeclaredAnnotations()  {
606         return super.getDeclaredAnnotations();
607     }
608 
609     /**
610      * {@inheritDoc}
611      * @since 1.5
612      */
613     @Override
614     public Annotation[][] getParameterAnnotations() {
615         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
616     }
617 
618     @Override
619     boolean handleParameterNumberMismatch(int resultLength, Class<?>[] parameterTypes) {
620         int numParameters = parameterTypes.length;
621         Class<?> declaringClass = getDeclaringClass();
622         if (declaringClass.isEnum()) {
623             return resultLength + 2 == numParameters &&
624                     parameterTypes[0] == String.class &&
625                     parameterTypes[1] == int.class;
626         } else if (
627             declaringClass.isAnonymousClass() ||
628             declaringClass.isLocalClass() )
629             return false; // Can't do reliable parameter counting
630         else {
631             if (declaringClass.isMemberClass() &&
632                 ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
633                 resultLength + 1 == numParameters) {
634                 return true;
635             } else {
636                 throw new AnnotationFormatError(
637                           "Parameter annotations don't match number of parameters");
638             }
639         }
640     }
641 
642     /**
643      * {@inheritDoc}
644      * @since 1.8
645      */
646     @Override
647     public AnnotatedType getAnnotatedReturnType() {
648         return getAnnotatedReturnType0(getDeclaringClass());
649     }
650 
651     /**
652      * {@inheritDoc}
653      * @since 1.8
654      */
655     @Override
656     public AnnotatedType getAnnotatedReceiverType() {
657         Class<?> thisDeclClass = getDeclaringClass();
658         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
659 
660         if (enclosingClass == null) {
661             // A Constructor for a top-level class
662             return null;
663         }
664 
665         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
666         if (outerDeclaringClass == null) {
667             // A constructor for a local or anonymous class
668             return null;
669         }
670 
671         // Either static nested or inner class
672         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
673             // static nested
674             return null;
675         }
676 
677         // A Constructor for an inner class
678         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
679                 SharedSecrets.getJavaLangAccess().
680                     getConstantPool(thisDeclClass),
681                 this,
682                 thisDeclClass,
683                 parameterize(enclosingClass),
684                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
685     }
686 }