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