1 /* 2 * Copyright (c) 2012, 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 java.lang.annotation.*; 29 import java.util.Map; 30 import java.util.Objects; 31 import sun.reflect.annotation.AnnotationParser; 32 import sun.reflect.annotation.AnnotationSupport; 33 import sun.reflect.annotation.TypeAnnotationParser; 34 import sun.reflect.annotation.TypeAnnotation; 35 import sun.reflect.generics.repository.ConstructorRepository; 36 37 /** 38 * A shared superclass for the common functionality of {@link Method} 39 * and {@link Constructor}. 40 * 41 * @since 1.8 42 */ 43 public abstract class Executable extends AccessibleObject 44 implements Member, GenericDeclaration { 45 /* 46 * Only grant package-visibility to the constructor. 47 */ 48 Executable() {} 49 50 /** 51 * Accessor method to allow code sharing 52 */ 53 abstract byte[] getAnnotationBytes(); 54 55 /** 56 * Does the Executable have generic information. 57 */ 58 abstract boolean hasGenericInformation(); 59 60 abstract ConstructorRepository getGenericInfo(); 61 62 boolean equalParamTypes(Class<?>[] params1, Class<?>[] params2) { 63 /* Avoid unnecessary cloning */ 64 if (params1.length == params2.length) { 65 for (int i = 0; i < params1.length; i++) { 66 if (params1[i] != params2[i]) 67 return false; 68 } 69 return true; 70 } 71 return false; 72 } 73 74 Annotation[][] parseParameterAnnotations(byte[] parameterAnnotations) { 75 return AnnotationParser.parseParameterAnnotations( 76 parameterAnnotations, 77 sun.misc.SharedSecrets.getJavaLangAccess(). 78 getConstantPool(getDeclaringClass()), 79 getDeclaringClass()); 80 } 81 82 void separateWithCommas(Class<?>[] types, StringBuilder sb) { 83 for (int j = 0; j < types.length; j++) { 84 sb.append(types[j].getTypeName()); 85 if (j < (types.length - 1)) 86 sb.append(","); 87 } 88 89 } 90 91 void printModifiersIfNonzero(StringBuilder sb, int mask, boolean isDefault) { 92 int mod = getModifiers() & mask; 93 94 if (mod != 0 && !isDefault) { 95 sb.append(Modifier.toString(mod)).append(' '); 96 } else { 97 int access_mod = mod & Modifier.ACCESS_MODIFIERS; 98 if (access_mod != 0) 99 sb.append(Modifier.toString(access_mod)).append(' '); 100 if (isDefault) 101 sb.append("default "); 102 mod = (mod & ~Modifier.ACCESS_MODIFIERS); 103 if (mod != 0) 104 sb.append(Modifier.toString(mod)).append(' '); 105 } 106 } 107 108 String sharedToString(int modifierMask, 109 boolean isDefault, 110 Class<?>[] parameterTypes, 111 Class<?>[] exceptionTypes) { 112 try { 113 StringBuilder sb = new StringBuilder(); 114 115 printModifiersIfNonzero(sb, modifierMask, isDefault); 116 specificToStringHeader(sb); 117 118 sb.append('('); 119 separateWithCommas(parameterTypes, sb); 120 sb.append(')'); 121 if (exceptionTypes.length > 0) { 122 sb.append(" throws "); 123 separateWithCommas(exceptionTypes, sb); 124 } 125 return sb.toString(); 126 } catch (Exception e) { 127 return "<" + e + ">"; 128 } 129 } 130 131 /** 132 * Generate toString header information specific to a method or 133 * constructor. 134 */ 135 abstract void specificToStringHeader(StringBuilder sb); 136 137 String sharedToGenericString(int modifierMask, boolean isDefault) { 138 try { 139 StringBuilder sb = new StringBuilder(); 140 141 printModifiersIfNonzero(sb, modifierMask, isDefault); 142 143 TypeVariable<?>[] typeparms = getTypeParameters(); 144 if (typeparms.length > 0) { 145 boolean first = true; 146 sb.append('<'); 147 for(TypeVariable<?> typeparm: typeparms) { 148 if (!first) 149 sb.append(','); 150 // Class objects can't occur here; no need to test 151 // and call Class.getName(). 152 sb.append(typeparm.toString()); 153 first = false; 154 } 155 sb.append("> "); 156 } 157 158 specificToGenericStringHeader(sb); 159 160 sb.append('('); 161 Type[] params = getGenericParameterTypes(); 162 for (int j = 0; j < params.length; j++) { 163 String param = params[j].getTypeName(); 164 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T... 165 param = param.replaceFirst("\\[\\]$", "..."); 166 sb.append(param); 167 if (j < (params.length - 1)) 168 sb.append(','); 169 } 170 sb.append(')'); 171 Type[] exceptions = getGenericExceptionTypes(); 172 if (exceptions.length > 0) { 173 sb.append(" throws "); 174 for (int k = 0; k < exceptions.length; k++) { 175 sb.append((exceptions[k] instanceof Class)? 176 ((Class)exceptions[k]).getName(): 177 exceptions[k].toString()); 178 if (k < (exceptions.length - 1)) 179 sb.append(','); 180 } 181 } 182 return sb.toString(); 183 } catch (Exception e) { 184 return "<" + e + ">"; 185 } 186 } 187 188 /** 189 * Generate toGenericString header information specific to a 190 * method or constructor. 191 */ 192 abstract void specificToGenericStringHeader(StringBuilder sb); 193 194 /** 195 * Returns the {@code Class} object representing the class or interface 196 * that declares the executable represented by this object. 197 */ 198 public abstract Class<?> getDeclaringClass(); 199 200 /** 201 * Returns the name of the executable represented by this object. 202 */ 203 public abstract String getName(); 204 205 /** 206 * Returns the Java language {@linkplain Modifier modifiers} for 207 * the executable represented by this object. 208 */ 209 public abstract int getModifiers(); 210 211 /** 212 * Returns an array of {@code TypeVariable} objects that represent the 213 * type variables declared by the generic declaration represented by this 214 * {@code GenericDeclaration} object, in declaration order. Returns an 215 * array of length 0 if the underlying generic declaration declares no type 216 * variables. 217 * 218 * @return an array of {@code TypeVariable} objects that represent 219 * the type variables declared by this generic declaration 220 * @throws GenericSignatureFormatError if the generic 221 * signature of this generic declaration does not conform to 222 * the format specified in 223 * <cite>The Java™ Virtual Machine Specification</cite> 224 */ 225 public abstract TypeVariable<?>[] getTypeParameters(); 226 227 /** 228 * Returns an array of {@code Class} objects that represent the formal 229 * parameter types, in declaration order, of the executable 230 * represented by this object. Returns an array of length 231 * 0 if the underlying executable takes no parameters. 232 * 233 * @return the parameter types for the executable this object 234 * represents 235 */ 236 public abstract Class<?>[] getParameterTypes(); 237 238 /** 239 * Returns the number of formal parameters (whether explicitly 240 * declared or implicitly declared or neither) for the executable 241 * represented by this object. 242 * 243 * @return The number of formal parameters for the executable this 244 * object represents 245 */ 246 public int getParameterCount() { 247 throw new AbstractMethodError(); 248 } 249 250 /** 251 * Returns an array of {@code Type} objects that represent the formal 252 * parameter types, in declaration order, of the executable represented by 253 * this object. Returns an array of length 0 if the 254 * underlying executable takes no parameters. 255 * 256 * <p>If a formal parameter type is a parameterized type, 257 * the {@code Type} object returned for it must accurately reflect 258 * the actual type parameters used in the source code. 259 * 260 * <p>If a formal parameter type is a type variable or a parameterized 261 * type, it is created. Otherwise, it is resolved. 262 * 263 * @return an array of {@code Type}s that represent the formal 264 * parameter types of the underlying executable, in declaration order 265 * @throws GenericSignatureFormatError 266 * if the generic method signature does not conform to the format 267 * specified in 268 * <cite>The Java™ Virtual Machine Specification</cite> 269 * @throws TypeNotPresentException if any of the parameter 270 * types of the underlying executable refers to a non-existent type 271 * declaration 272 * @throws MalformedParameterizedTypeException if any of 273 * the underlying executable's parameter types refer to a parameterized 274 * type that cannot be instantiated for any reason 275 */ 276 public Type[] getGenericParameterTypes() { 277 if (hasGenericInformation()) 278 return getGenericInfo().getParameterTypes(); 279 else 280 return getParameterTypes(); 281 } 282 283 /** 284 * Returns an array of {@code Parameter} objects that represent 285 * all the parameters to the underlying executable represented by 286 * this object. Returns an array of length 0 if the executable 287 * has no parameters. 288 * 289 * <p>The parameters of the underlying executable do not necessarily 290 * have unique names, or names that are legal identifiers in the 291 * Java programming language (JLS 3.8). 292 * 293 * @throws MalformedParametersException if the class file contains 294 * a MethodParameters attribute that is improperly formatted. 295 * @return an array of {@code Parameter} objects representing all 296 * the parameters to the executable this object represents. 297 */ 298 public Parameter[] getParameters() { 299 // TODO: This may eventually need to be guarded by security 300 // mechanisms similar to those in Field, Method, etc. 301 // 302 // Need to copy the cached array to prevent users from messing 303 // with it. Since parameters are immutable, we can 304 // shallow-copy. 305 return privateGetParameters().clone(); 306 } 307 308 private Parameter[] synthesizeAllParams() { 309 final int realparams = getParameterCount(); 310 final Parameter[] out = new Parameter[realparams]; 311 for (int i = 0; i < realparams; i++) 312 // TODO: is there a way to synthetically derive the 313 // modifiers? Probably not in the general case, since 314 // we'd have no way of knowing about them, but there 315 // may be specific cases. 316 out[i] = new Parameter("arg" + i, 0, this, i); 317 return out; 318 } 319 320 private void verifyParameters(final Parameter[] parameters) { 321 final int mask = Modifier.FINAL | Modifier.SYNTHETIC | Modifier.MANDATED; 322 323 if (getParameterTypes().length != parameters.length) 324 throw new MalformedParametersException("Wrong number of parameters in MethodParameters attribute"); 325 326 for (Parameter parameter : parameters) { 327 final String name = parameter.getRealName(); 328 final int mods = parameter.getModifiers(); 329 330 if (name != null) { 331 if (name.isEmpty() || name.indexOf('.') != -1 || 332 name.indexOf(';') != -1 || name.indexOf('[') != -1 || 333 name.indexOf('/') != -1) { 334 throw new MalformedParametersException("Invalid parameter name \"" + name + "\""); 335 } 336 } 337 338 if (mods != (mods & mask)) { 339 throw new MalformedParametersException("Invalid parameter modifiers"); 340 } 341 } 342 } 343 344 private Parameter[] privateGetParameters() { 345 // Use tmp to avoid multiple writes to a volatile. 346 Parameter[] tmp = parameters; 347 348 if (tmp == null) { 349 350 // Otherwise, go to the JVM to get them 351 try { 352 tmp = getParameters0(); 353 } catch(IllegalArgumentException e) { 354 // Rethrow ClassFormatErrors 355 throw new MalformedParametersException("Invalid constant pool index"); 356 } 357 358 // If we get back nothing, then synthesize parameters 359 if (tmp == null) { 360 hasRealParameterData = false; 361 tmp = synthesizeAllParams(); 362 } else { 363 hasRealParameterData = true; 364 verifyParameters(tmp); 365 } 366 367 parameters = tmp; 368 } 369 370 return tmp; 371 } 372 373 boolean hasRealParameterData() { 374 // If this somehow gets called before parameters gets 375 // initialized, force it into existence. 376 if (parameters == null) { 377 privateGetParameters(); 378 } 379 return hasRealParameterData; 380 } 381 382 private transient volatile boolean hasRealParameterData; 383 private transient volatile Parameter[] parameters; 384 385 private native Parameter[] getParameters0(); 386 native byte[] getTypeAnnotationBytes0(); 387 388 // Needed by reflectaccess 389 byte[] getTypeAnnotationBytes() { 390 return getTypeAnnotationBytes0(); 391 } 392 393 /** 394 * Returns an array of {@code Class} objects that represent the 395 * types of exceptions declared to be thrown by the underlying 396 * executable represented by this object. Returns an array of 397 * length 0 if the executable declares no exceptions in its {@code 398 * throws} clause. 399 * 400 * @return the exception types declared as being thrown by the 401 * executable this object represents 402 */ 403 public abstract Class<?>[] getExceptionTypes(); 404 405 /** 406 * Returns an array of {@code Type} objects that represent the 407 * exceptions declared to be thrown by this executable object. 408 * Returns an array of length 0 if the underlying executable declares 409 * no exceptions in its {@code throws} clause. 410 * 411 * <p>If an exception type is a type variable or a parameterized 412 * type, it is created. Otherwise, it is resolved. 413 * 414 * @return an array of Types that represent the exception types 415 * thrown by the underlying executable 416 * @throws GenericSignatureFormatError 417 * if the generic method signature does not conform to the format 418 * specified in 419 * <cite>The Java™ Virtual Machine Specification</cite> 420 * @throws TypeNotPresentException if the underlying executable's 421 * {@code throws} clause refers to a non-existent type declaration 422 * @throws MalformedParameterizedTypeException if 423 * the underlying executable's {@code throws} clause refers to a 424 * parameterized type that cannot be instantiated for any reason 425 */ 426 public Type[] getGenericExceptionTypes() { 427 Type[] result; 428 if (hasGenericInformation() && 429 ((result = getGenericInfo().getExceptionTypes()).length > 0)) 430 return result; 431 else 432 return getExceptionTypes(); 433 } 434 435 /** 436 * Returns a string describing this {@code Executable}, including 437 * any type parameters. 438 * @return a string describing this {@code Executable}, including 439 * any type parameters 440 */ 441 public abstract String toGenericString(); 442 443 /** 444 * Returns {@code true} if this executable was declared to take a 445 * variable number of arguments; returns {@code false} otherwise. 446 * 447 * @return {@code true} if an only if this executable was declared 448 * to take a variable number of arguments. 449 */ 450 public boolean isVarArgs() { 451 return (getModifiers() & Modifier.VARARGS) != 0; 452 } 453 454 /** 455 * Returns {@code true} if this executable is a synthetic 456 * construct; returns {@code false} otherwise. 457 * 458 * @return true if and only if this executable is a synthetic 459 * construct as defined by 460 * <cite>The Java™ Language Specification</cite>. 461 * @jls 13.1 The Form of a Binary 462 */ 463 public boolean isSynthetic() { 464 return Modifier.isSynthetic(getModifiers()); 465 } 466 467 /** 468 * Returns an array of arrays of {@code Annotation}s that 469 * represent the annotations on the formal parameters, in 470 * declaration order, of the {@code Executable} represented by 471 * this object. Synthetic and mandated parameters (see 472 * explanation below), such as the outer "this" parameter to an 473 * inner class constructor will be represented in the returned 474 * array. If the executable has no parameters (meaning no formal, 475 * no synthetic, and no mandated parameters), a zero-length array 476 * will be returned. If the {@code Executable} has one or more 477 * parameters, a nested array of length zero is returned for each 478 * parameter with no annotations. The annotation objects contained 479 * in the returned arrays are serializable. The caller of this 480 * method is free to modify the returned arrays; it will have no 481 * effect on the arrays returned to other callers. 482 * 483 * A compiler may add extra parameters that are implicitly 484 * declared in source ("mandated"), as well as parameters that 485 * are neither implicitly nor explicitly declared in source 486 * ("synthetic") to the parameter list for a method. See {@link 487 * java.lang.reflect.Parameter} for more information. 488 * 489 * @see java.lang.reflect.Parameter 490 * @see java.lang.reflect.Parameter#getAnnotations 491 * @return an array of arrays that represent the annotations on 492 * the formal and implicit parameters, in declaration order, of 493 * the executable represented by this object 494 */ 495 public abstract Annotation[][] getParameterAnnotations(); 496 497 Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes, 498 byte[] parameterAnnotations) { 499 int numParameters = parameterTypes.length; 500 if (parameterAnnotations == null) 501 return new Annotation[numParameters][0]; 502 503 Annotation[][] result = parseParameterAnnotations(parameterAnnotations); 504 505 if (result.length != numParameters) 506 handleParameterNumberMismatch(result.length, numParameters); 507 return result; 508 } 509 510 abstract void handleParameterNumberMismatch(int resultLength, int numParameters); 511 512 /** 513 * {@inheritDoc} 514 * @throws NullPointerException {@inheritDoc} 515 */ 516 public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { 517 Objects.requireNonNull(annotationClass); 518 return annotationClass.cast(declaredAnnotations().get(annotationClass)); 519 } 520 521 /** 522 * {@inheritDoc} 523 * @throws NullPointerException {@inheritDoc} 524 */ 525 @Override 526 public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { 527 Objects.requireNonNull(annotationClass); 528 529 return AnnotationSupport.getDirectlyAndIndirectlyPresent(declaredAnnotations(), annotationClass); 530 } 531 532 /** 533 * {@inheritDoc} 534 */ 535 public Annotation[] getDeclaredAnnotations() { 536 return AnnotationParser.toArray(declaredAnnotations()); 537 } 538 539 private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations; 540 541 private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() { 542 if (declaredAnnotations == null) { 543 declaredAnnotations = AnnotationParser.parseAnnotations( 544 getAnnotationBytes(), 545 sun.misc.SharedSecrets.getJavaLangAccess(). 546 getConstantPool(getDeclaringClass()), 547 getDeclaringClass()); 548 } 549 return declaredAnnotations; 550 } 551 552 /** 553 * Returns an {@code AnnotatedType} object that represents the use of a type to 554 * specify the return type of the method/constructor represented by this 555 * Executable. 556 * 557 * If this {@code Executable} object represents a constructor, the {@code 558 * AnnotatedType} object represents the type of the constructed object. 559 * 560 * If this {@code Executable} object represents a method, the {@code 561 * AnnotatedType} object represents the use of a type to specify the return 562 * type of the method. 563 * 564 * @return an object representing the return type of the method 565 * or constructor represented by this {@code Executable} 566 */ 567 public abstract AnnotatedType getAnnotatedReturnType(); 568 569 /* Helper for subclasses of Executable. 570 * 571 * Returns an AnnotatedType object that represents the use of a type to 572 * specify the return type of the method/constructor represented by this 573 * Executable. 574 */ 575 AnnotatedType getAnnotatedReturnType0(Type returnType) { 576 return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(), 577 sun.misc.SharedSecrets.getJavaLangAccess(). 578 getConstantPool(getDeclaringClass()), 579 this, 580 getDeclaringClass(), 581 returnType, 582 TypeAnnotation.TypeAnnotationTarget.METHOD_RETURN); 583 } 584 585 /** 586 * Returns an {@code AnnotatedType} object that represents the use of a 587 * type to specify the receiver type of the method/constructor represented 588 * by this {@code Executable} object. 589 * 590 * The receiver type of a method/constructor is available only if the 591 * method/constructor has a receiver parameter (JLS 8.4.1). If this {@code 592 * Executable} object <em>represents an instance method or represents a 593 * constructor of an inner member class</em>, and the 594 * method/constructor <em>either</em> has no receiver parameter or has a 595 * receiver parameter with no annotations on its type, then the return 596 * value is an {@code AnnotatedType} object representing an element with no 597 * annotations. 598 * 599 * If this {@code Executable} object represents a static method or 600 * represents a constructor of a top level, static member, local, or 601 * anoymous class, then the return value is null. 602 * 603 * @return an object representing the receiver type of the method or 604 * constructor represented by this {@code Executable} or {@code null} if 605 * this {@code Executable} can not have a receiver parameter 606 */ 607 public AnnotatedType getAnnotatedReceiverType() { 608 if (Modifier.isStatic(this.getModifiers())) 609 return null; 610 return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(), 611 sun.misc.SharedSecrets.getJavaLangAccess(). 612 getConstantPool(getDeclaringClass()), 613 this, 614 getDeclaringClass(), 615 getDeclaringClass(), 616 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER); 617 } 618 619 /** 620 * Returns an array of {@code AnnotatedType} objects that represent the use 621 * of types to specify formal parameter types of the method/constructor 622 * represented by this Executable. The order of the objects in the array 623 * corresponds to the order of the formal parameter types in the 624 * declaration of the method/constructor. 625 * 626 * Returns an array of length 0 if the method/constructor declares no 627 * parameters. 628 * 629 * @return an array of objects representing the types of the 630 * formal parameters of the method or constructor represented by this 631 * {@code Executable} 632 */ 633 public AnnotatedType[] getAnnotatedParameterTypes() { 634 return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(), 635 sun.misc.SharedSecrets.getJavaLangAccess(). 636 getConstantPool(getDeclaringClass()), 637 this, 638 getDeclaringClass(), 639 getGenericParameterTypes(), 640 TypeAnnotation.TypeAnnotationTarget.METHOD_FORMAL_PARAMETER); 641 } 642 643 /** 644 * Returns an array of {@code AnnotatedType} objects that represent the use 645 * of types to specify the declared exceptions of the method/constructor 646 * represented by this Executable. The order of the objects in the array 647 * corresponds to the order of the exception types in the declaration of 648 * the method/constructor. 649 * 650 * Returns an array of length 0 if the method/constructor declares no 651 * exceptions. 652 * 653 * @return an array of objects representing the declared 654 * exceptions of the method or constructor represented by this {@code 655 * Executable} 656 */ 657 public AnnotatedType[] getAnnotatedExceptionTypes() { 658 return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(), 659 sun.misc.SharedSecrets.getJavaLangAccess(). 660 getConstantPool(getDeclaringClass()), 661 this, 662 getDeclaringClass(), 663 getGenericExceptionTypes(), 664 TypeAnnotation.TypeAnnotationTarget.THROWS); 665 } 666 667 }