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