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