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