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.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.repository.GenericDeclRepository; 39 import sun.reflect.generics.factory.CoreReflectionFactory; 40 import sun.reflect.generics.factory.GenericsFactory; 41 import sun.reflect.generics.scope.ConstructorScope; 42 import java.lang.annotation.Annotation; 43 import java.lang.annotation.AnnotationFormatError; 44 import java.util.StringJoiner; 45 46 /** 47 * {@code Constructor} provides information about, and access to, a single 48 * constructor for a class. 49 * 50 * <p>{@code Constructor} permits widening conversions to occur when matching the 51 * actual parameters to newInstance() with the underlying 52 * constructor's formal parameters, but throws an 53 * {@code IllegalArgumentException} if a narrowing conversion would occur. 54 * 55 * @param <T> the class in which the constructor is declared 56 * 57 * @see Member 58 * @see java.lang.Class 59 * @see java.lang.Class#getConstructors() 60 * @see java.lang.Class#getConstructor(Class[]) 61 * @see java.lang.Class#getDeclaredConstructors() 62 * 63 * @author Kenneth Russell 64 * @author Nakul Saraiya 65 * @since 1.1 66 */ 67 public final class Constructor<T> extends Executable { 68 private final Class<T> clazz; 69 private final int slot; 70 private final Class<?>[] parameterTypes; 71 private final Class<?>[] exceptionTypes; 72 private final int modifiers; 73 // Generics and annotations support 74 private final transient String signature; 75 // generic info repository; lazily initialized 76 private transient ConstructorRepository genericInfo; 77 private final byte[] annotations; 78 private final 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>>[])GenericDeclRepository.EMPTY_TYPE_VARS; 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 : getSharedParameterTypes()) { 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 ConstructorAccessor ca = constructorAccessor; // read @Stable 496 if (ca == null) { 497 ca = acquireConstructorAccessor(); 498 } 499 @SuppressWarnings("unchecked") 500 T inst = (T) ca.newInstance(args); 501 return inst; 502 } 503 504 /** 505 * {@inheritDoc} 506 * @since 1.5 507 * @jls 8.4.1 Formal Parameters 508 */ 509 @Override 510 public boolean isVarArgs() { 511 return super.isVarArgs(); 512 } 513 514 /** 515 * {@inheritDoc} 516 * @jls 13.1 The Form of a Binary 517 * @jvms 4.6 Methods 518 * @since 1.5 519 * @see <a 520 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java 521 * programming language and JVM modeling in core reflection</a> 522 */ 523 @Override 524 public boolean isSynthetic() { 525 return super.isSynthetic(); 526 } 527 528 // NOTE that there is no synchronization used here. It is correct 529 // (though not efficient) to generate more than one 530 // ConstructorAccessor for a given Constructor. However, avoiding 531 // synchronization will probably make the implementation more 532 // scalable. 533 private ConstructorAccessor acquireConstructorAccessor() { 534 535 // First check to see if one has been created yet, and take it 536 // if so. 537 Constructor<?> root = this.root; 538 ConstructorAccessor tmp = root == null ? null : root.getConstructorAccessor(); 539 if (tmp != null) { 540 constructorAccessor = tmp; 541 } else { 542 // Otherwise fabricate one and propagate it up to the root 543 // Ensure the declaring class is not an Enum class. 544 if ((clazz.getModifiers() & Modifier.ENUM) != 0) 545 throw new IllegalArgumentException("Cannot reflectively create enum objects"); 546 547 tmp = reflectionFactory.newConstructorAccessor(this); 548 // set the constructor accessor only if it's not using native implementation 549 if (VM.isJavaLangInvokeInited()) 550 setConstructorAccessor(tmp); 551 } 552 553 return tmp; 554 } 555 556 // Returns ConstructorAccessor for this Constructor object, not 557 // looking up the chain to the root 558 ConstructorAccessor getConstructorAccessor() { 559 return constructorAccessor; 560 } 561 562 // Sets the ConstructorAccessor for this Constructor object and 563 // (recursively) its root 564 void setConstructorAccessor(ConstructorAccessor accessor) { 565 constructorAccessor = accessor; 566 // Propagate up 567 Constructor<?> root = this.root; 568 if (root != null) { 569 root.setConstructorAccessor(accessor); 570 } 571 } 572 573 int getSlot() { 574 return slot; 575 } 576 577 String getSignature() { 578 return signature; 579 } 580 581 byte[] getRawAnnotations() { 582 return annotations; 583 } 584 585 byte[] getRawParameterAnnotations() { 586 return parameterAnnotations; 587 } 588 589 590 /** 591 * {@inheritDoc} 592 * 593 * @throws NullPointerException {@inheritDoc} 594 * @since 1.5 595 */ 596 @Override 597 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { 598 return super.getAnnotation(annotationClass); 599 } 600 601 /** 602 * {@inheritDoc} 603 * @since 1.5 604 */ 605 @Override 606 public Annotation[] getDeclaredAnnotations() { 607 return super.getDeclaredAnnotations(); 608 } 609 610 /** 611 * {@inheritDoc} 612 * @since 1.5 613 */ 614 @Override 615 public Annotation[][] getParameterAnnotations() { 616 return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations); 617 } 618 619 @Override 620 boolean handleParameterNumberMismatch(int resultLength, Class<?>[] parameterTypes) { 621 int numParameters = parameterTypes.length; 622 Class<?> declaringClass = getDeclaringClass(); 623 if (declaringClass.isEnum()) { 624 return resultLength + 2 == numParameters && 625 parameterTypes[0] == String.class && 626 parameterTypes[1] == int.class; 627 } else if ( 628 declaringClass.isAnonymousClass() || 629 declaringClass.isLocalClass() ) 630 return false; // Can't do reliable parameter counting 631 else { 632 if (declaringClass.isMemberClass() && 633 ((declaringClass.getModifiers() & Modifier.STATIC) == 0) && 634 resultLength + 1 == numParameters) { 635 return true; 636 } else { 637 throw new AnnotationFormatError( 638 "Parameter annotations don't match number of parameters"); 639 } 640 } 641 } 642 643 /** 644 * {@inheritDoc} 645 * @since 1.8 646 */ 647 @Override 648 public AnnotatedType getAnnotatedReturnType() { 649 return getAnnotatedReturnType0(getDeclaringClass()); 650 } 651 652 /** 653 * {@inheritDoc} 654 * @since 1.8 655 */ 656 @Override 657 public AnnotatedType getAnnotatedReceiverType() { 658 Class<?> thisDeclClass = getDeclaringClass(); 659 Class<?> enclosingClass = thisDeclClass.getEnclosingClass(); 660 661 if (enclosingClass == null) { 662 // A Constructor for a top-level class 663 return null; 664 } 665 666 Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass(); 667 if (outerDeclaringClass == null) { 668 // A constructor for a local or anonymous class 669 return null; 670 } 671 672 // Either static nested or inner class 673 if (Modifier.isStatic(thisDeclClass.getModifiers())) { 674 // static nested 675 return null; 676 } 677 678 // A Constructor for an inner class 679 return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(), 680 SharedSecrets.getJavaLangAccess(). 681 getConstantPool(thisDeclClass), 682 this, 683 thisDeclClass, 684 parameterize(enclosingClass), 685 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER); 686 } 687 }