1 /* 2 * Copyright (c) 2008, 2012, 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.invoke; 27 28 import sun.invoke.util.BytecodeDescriptor; 29 import sun.invoke.util.VerifyAccess; 30 31 import java.lang.reflect.Constructor; 32 import java.lang.reflect.Field; 33 import java.lang.reflect.Method; 34 import java.lang.reflect.Member; 35 import java.lang.reflect.Modifier; 36 import java.util.ArrayList; 37 import java.util.Arrays; 38 import java.util.Collections; 39 import java.util.Iterator; 40 import java.util.List; 41 import static java.lang.invoke.MethodHandleNatives.Constants.*; 42 import static java.lang.invoke.MethodHandleStatics.*; 43 import java.util.Objects; 44 45 /** 46 * A {@code MemberName} is a compact symbolic datum which fully characterizes 47 * a method or field reference. 48 * A member name refers to a field, method, constructor, or member type. 49 * Every member name has a simple name (a string) and a type (either a Class or MethodType). 50 * A member name may also have a non-null declaring class, or it may be simply 51 * a naked name/type pair. 52 * A member name may also have non-zero modifier flags. 53 * Finally, a member name may be either resolved or unresolved. 54 * If it is resolved, the existence of the named 55 * <p> 56 * Whether resolved or not, a member name provides no access rights or 57 * invocation capability to its possessor. It is merely a compact 58 * representation of all symbolic information necessary to link to 59 * and properly use the named member. 60 * <p> 61 * When resolved, a member name's internal implementation may include references to JVM metadata. 62 * This representation is stateless and only decriptive. 63 * It provides no private information and no capability to use the member. 64 * <p> 65 * By contrast, a {@linkplain java.lang.reflect.Method} contains fuller information 66 * about the internals of a method (except its bytecodes) and also 67 * allows invocation. A MemberName is much lighter than a Method, 68 * since it contains about 7 fields to the 16 of Method (plus its sub-arrays), 69 * and those seven fields omit much of the information in Method. 70 * @author jrose 71 */ 72 /*non-public*/ final class MemberName implements Member, Cloneable { 73 private Class<?> clazz; // class in which the method is defined 74 private String name; // may be null if not yet materialized 75 private Object type; // may be null if not yet materialized 76 private int flags; // modifier bits; see reflect.Modifier 77 //@Injected JVM_Method* vmtarget; 78 //@Injected int vmindex; 79 private Object resolution; // if null, this guy is resolved 80 81 /** Return the declaring class of this member. 82 * In the case of a bare name and type, the declaring class will be null. 83 */ 84 public Class<?> getDeclaringClass() { 85 return clazz; 86 } 87 88 /** Utility method producing the class loader of the declaring class. */ 89 public ClassLoader getClassLoader() { 90 return clazz.getClassLoader(); 91 } 92 93 /** Return the simple name of this member. 94 * For a type, it is the same as {@link Class#getSimpleName}. 95 * For a method or field, it is the simple name of the member. 96 * For a constructor, it is always {@code "<init>"}. 97 */ 98 public String getName() { 99 if (name == null) { 100 expandFromVM(); 101 if (name == null) return null; 102 } 103 return name; 104 } 105 106 public MethodType getMethodOrFieldType() { 107 if (isInvocable()) 108 return getMethodType(); 109 if (isGetter()) 110 return MethodType.methodType(getFieldType()); 111 if (isSetter()) 112 return MethodType.methodType(void.class, getFieldType()); 113 throw new InternalError("not a method or field: "+this); 114 } 115 116 /** Return the declared type of this member, which 117 * must be a method or constructor. 118 */ 119 public MethodType getMethodType() { 120 if (type == null) { 121 expandFromVM(); 122 if (type == null) return null; 123 } 124 if (!isInvocable()) 125 throw newIllegalArgumentException("not invocable, no method type"); 126 if (type instanceof MethodType) { 127 return (MethodType) type; 128 } 129 if (type instanceof String) { 130 String sig = (String) type; 131 MethodType res = MethodType.fromMethodDescriptorString(sig, getClassLoader()); 132 this.type = res; 133 return res; 134 } 135 if (type instanceof Object[]) { 136 Object[] typeInfo = (Object[]) type; 137 Class<?>[] ptypes = (Class<?>[]) typeInfo[1]; 138 Class<?> rtype = (Class<?>) typeInfo[0]; 139 MethodType res = MethodType.methodType(rtype, ptypes); 140 this.type = res; 141 return res; 142 } 143 throw new InternalError("bad method type "+type); 144 } 145 146 /** Return the actual type under which this method or constructor must be invoked. 147 * For non-static methods or constructors, this is the type with a leading parameter, 148 * a reference to declaring class. For static methods, it is the same as the declared type. 149 */ 150 public MethodType getInvocationType() { 151 MethodType itype = getMethodOrFieldType(); 152 if (isConstructor() && getReferenceKind() == REF_newInvokeSpecial) 153 return itype.changeReturnType(clazz); 154 if (!isStatic()) 155 return itype.insertParameterTypes(0, clazz); 156 return itype; 157 } 158 159 /** Utility method producing the parameter types of the method type. */ 160 public Class<?>[] getParameterTypes() { 161 return getMethodType().parameterArray(); 162 } 163 164 /** Utility method producing the return type of the method type. */ 165 public Class<?> getReturnType() { 166 return getMethodType().returnType(); 167 } 168 169 /** Return the declared type of this member, which 170 * must be a field or type. 171 * If it is a type member, that type itself is returned. 172 */ 173 public Class<?> getFieldType() { 174 if (type == null) { 175 expandFromVM(); 176 if (type == null) return null; 177 } 178 if (isInvocable()) 179 throw newIllegalArgumentException("not a field or nested class, no simple type"); 180 if (type instanceof Class<?>) { 181 return (Class<?>) type; 182 } 183 if (type instanceof String) { 184 String sig = (String) type; 185 MethodType mtype = MethodType.fromMethodDescriptorString("()"+sig, getClassLoader()); 186 Class<?> res = mtype.returnType(); 187 this.type = res; 188 return res; 189 } 190 throw new InternalError("bad field type "+type); 191 } 192 193 /** Utility method to produce either the method type or field type of this member. */ 194 public Object getType() { 195 return (isInvocable() ? getMethodType() : getFieldType()); 196 } 197 198 /** Utility method to produce the signature of this member, 199 * used within the class file format to describe its type. 200 */ 201 public String getSignature() { 202 if (type == null) { 203 expandFromVM(); 204 if (type == null) return null; 205 } 206 if (type instanceof String) 207 return (String) type; 208 if (isInvocable()) 209 return BytecodeDescriptor.unparse(getMethodType()); 210 else 211 return BytecodeDescriptor.unparse(getFieldType()); 212 } 213 214 /** Return the modifier flags of this member. 215 * @see java.lang.reflect.Modifier 216 */ 217 public int getModifiers() { 218 return (flags & RECOGNIZED_MODIFIERS); 219 } 220 221 /** Return the reference kind of this member, or zero if none. 222 */ 223 public byte getReferenceKind() { 224 return (byte) ((flags >>> MN_REFERENCE_KIND_SHIFT) & MN_REFERENCE_KIND_MASK); 225 } 226 private boolean referenceKindIsConsistent() { 227 byte refKind = getReferenceKind(); 228 if (refKind == REF_NONE) return isType(); 229 if (isField()) { 230 assert(staticIsConsistent()); 231 assert(MethodHandleNatives.refKindIsField(refKind)); 232 } else if (isConstructor()) { 233 assert(refKind == REF_newInvokeSpecial || refKind == REF_invokeSpecial); 234 } else if (isMethod()) { 235 assert(staticIsConsistent()); 236 assert(MethodHandleNatives.refKindIsMethod(refKind)); 237 if (clazz.isInterface()) 238 assert(refKind == REF_invokeInterface || 239 refKind == REF_invokeStatic || 240 refKind == REF_invokeSpecial || 241 refKind == REF_invokeVirtual && isObjectPublicMethod()); 242 } else { 243 assert(false); 244 } 245 return true; 246 } 247 private boolean isObjectPublicMethod() { 248 if (clazz == Object.class) return true; 249 MethodType mtype = getMethodType(); 250 if (name.equals("toString") && mtype.returnType() == String.class && mtype.parameterCount() == 0) 251 return true; 252 if (name.equals("hashCode") && mtype.returnType() == int.class && mtype.parameterCount() == 0) 253 return true; 254 if (name.equals("equals") && mtype.returnType() == boolean.class && mtype.parameterCount() == 1 && mtype.parameterType(0) == Object.class) 255 return true; 256 return false; 257 } 258 /*non-public*/ boolean referenceKindIsConsistentWith(int originalRefKind) { 259 int refKind = getReferenceKind(); 260 if (refKind == originalRefKind) return true; 261 switch (originalRefKind) { 262 case REF_invokeInterface: 263 // Looking up an interface method, can get (e.g.) Object.hashCode 264 assert(refKind == REF_invokeVirtual || 265 refKind == REF_invokeSpecial) : this; 266 return true; 267 case REF_invokeVirtual: 268 case REF_newInvokeSpecial: 269 // Looked up a virtual, can get (e.g.) final String.hashCode. 270 assert(refKind == REF_invokeSpecial) : this; 271 return true; 272 } 273 assert(false) : this+" != "+MethodHandleNatives.refKindName((byte)originalRefKind); 274 return true; 275 } 276 private boolean staticIsConsistent() { 277 byte refKind = getReferenceKind(); 278 return MethodHandleNatives.refKindIsStatic(refKind) == isStatic() || getModifiers() == 0; 279 } 280 private boolean vminfoIsConsistent() { 281 byte refKind = getReferenceKind(); 282 assert(isResolved()); // else don't call 283 Object vminfo = MethodHandleNatives.getMemberVMInfo(this); 284 assert(vminfo instanceof Object[]); 285 long vmindex = (Long) ((Object[])vminfo)[0]; 286 Object vmtarget = ((Object[])vminfo)[1]; 287 if (MethodHandleNatives.refKindIsField(refKind)) { 288 assert(vmindex >= 0) : vmindex + ":" + this; 289 assert(vmtarget instanceof Class); 290 } else { 291 if (MethodHandleNatives.refKindDoesDispatch(refKind)) 292 assert(vmindex >= 0) : vmindex + ":" + this; 293 else 294 assert(vmindex < 0) : vmindex; 295 assert(vmtarget instanceof MemberName) : vmtarget + " in " + this; 296 } 297 return true; 298 } 299 300 private MemberName changeReferenceKind(byte refKind, byte oldKind) { 301 assert(getReferenceKind() == oldKind); 302 assert(MethodHandleNatives.refKindIsValid(refKind)); 303 flags += (((int)refKind - oldKind) << MN_REFERENCE_KIND_SHIFT); 304 // if (isConstructor() && refKind != REF_newInvokeSpecial) 305 // flags += (IS_METHOD - IS_CONSTRUCTOR); 306 // else if (refKind == REF_newInvokeSpecial && isMethod()) 307 // flags += (IS_CONSTRUCTOR - IS_METHOD); 308 return this; 309 } 310 311 private boolean testFlags(int mask, int value) { 312 return (flags & mask) == value; 313 } 314 private boolean testAllFlags(int mask) { 315 return testFlags(mask, mask); 316 } 317 private boolean testAnyFlags(int mask) { 318 return !testFlags(mask, 0); 319 } 320 321 /** Utility method to query if this member is a method handle invocation (invoke or invokeExact). */ 322 public boolean isMethodHandleInvoke() { 323 final int bits = Modifier.NATIVE | Modifier.FINAL; 324 final int negs = Modifier.STATIC; 325 if (testFlags(bits | negs, bits) && 326 clazz == MethodHandle.class) { 327 return name.equals("invoke") || name.equals("invokeExact"); 328 } 329 return false; 330 } 331 332 /** Utility method to query the modifier flags of this member. */ 333 public boolean isStatic() { 334 return Modifier.isStatic(flags); 335 } 336 /** Utility method to query the modifier flags of this member. */ 337 public boolean isPublic() { 338 return Modifier.isPublic(flags); 339 } 340 /** Utility method to query the modifier flags of this member. */ 341 public boolean isPrivate() { 342 return Modifier.isPrivate(flags); 343 } 344 /** Utility method to query the modifier flags of this member. */ 345 public boolean isProtected() { 346 return Modifier.isProtected(flags); 347 } 348 /** Utility method to query the modifier flags of this member. */ 349 public boolean isFinal() { 350 return Modifier.isFinal(flags); 351 } 352 /** Utility method to query whether this member or its defining class is final. */ 353 public boolean canBeStaticallyBound() { 354 return Modifier.isFinal(flags | clazz.getModifiers()); 355 } 356 /** Utility method to query the modifier flags of this member. */ 357 public boolean isVolatile() { 358 return Modifier.isVolatile(flags); 359 } 360 /** Utility method to query the modifier flags of this member. */ 361 public boolean isAbstract() { 362 return Modifier.isAbstract(flags); 363 } 364 /** Utility method to query the modifier flags of this member. */ 365 public boolean isNative() { 366 return Modifier.isNative(flags); 367 } 368 // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo 369 370 // unofficial modifier flags, used by HotSpot: 371 static final int BRIDGE = 0x00000040; 372 static final int VARARGS = 0x00000080; 373 static final int SYNTHETIC = 0x00001000; 374 static final int ANNOTATION= 0x00002000; 375 static final int ENUM = 0x00004000; 376 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 377 public boolean isBridge() { 378 return testAllFlags(IS_METHOD | BRIDGE); 379 } 380 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 381 public boolean isVarargs() { 382 return testAllFlags(VARARGS) && isInvocable(); 383 } 384 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 385 public boolean isSynthetic() { 386 return testAllFlags(SYNTHETIC); 387 } 388 389 static final String CONSTRUCTOR_NAME = "<init>"; // the ever-popular 390 391 // modifiers exported by the JVM: 392 static final int RECOGNIZED_MODIFIERS = 0xFFFF; 393 394 // private flags, not part of RECOGNIZED_MODIFIERS: 395 static final int 396 IS_METHOD = MN_IS_METHOD, // method (not constructor) 397 IS_CONSTRUCTOR = MN_IS_CONSTRUCTOR, // constructor 398 IS_FIELD = MN_IS_FIELD, // field 399 IS_TYPE = MN_IS_TYPE, // nested type 400 CALLER_SENSITIVE = MN_CALLER_SENSITIVE; // @CallerSensitive annotation detected 401 402 static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; 403 static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE; 404 static final int IS_INVOCABLE = IS_METHOD | IS_CONSTRUCTOR; 405 static final int IS_FIELD_OR_METHOD = IS_METHOD | IS_FIELD; 406 static final int SEARCH_ALL_SUPERS = MN_SEARCH_SUPERCLASSES | MN_SEARCH_INTERFACES; 407 408 /** Utility method to query whether this member is a method or constructor. */ 409 public boolean isInvocable() { 410 return testAnyFlags(IS_INVOCABLE); 411 } 412 /** Utility method to query whether this member is a method, constructor, or field. */ 413 public boolean isFieldOrMethod() { 414 return testAnyFlags(IS_FIELD_OR_METHOD); 415 } 416 /** Query whether this member is a method. */ 417 public boolean isMethod() { 418 return testAllFlags(IS_METHOD); 419 } 420 /** Query whether this member is a constructor. */ 421 public boolean isConstructor() { 422 return testAllFlags(IS_CONSTRUCTOR); 423 } 424 /** Query whether this member is a field. */ 425 public boolean isField() { 426 return testAllFlags(IS_FIELD); 427 } 428 /** Query whether this member is a type. */ 429 public boolean isType() { 430 return testAllFlags(IS_TYPE); 431 } 432 /** Utility method to query whether this member is neither public, private, nor protected. */ 433 public boolean isPackage() { 434 return !testAnyFlags(ALL_ACCESS); 435 } 436 /** Query whether this member has a CallerSensitive annotation. */ 437 public boolean isCallerSensitive() { 438 return testAllFlags(CALLER_SENSITIVE); 439 } 440 441 /** Utility method to query whether this member is accessible from a given lookup class. */ 442 public boolean isAccessibleFrom(Class<?> lookupClass) { 443 return VerifyAccess.isMemberAccessible(this.getDeclaringClass(), this.getDeclaringClass(), flags, 444 lookupClass, ALL_ACCESS|MethodHandles.Lookup.PACKAGE); 445 } 446 447 /** Initialize a query. It is not resolved. */ 448 private void init(Class<?> defClass, String name, Object type, int flags) { 449 // defining class is allowed to be null (for a naked name/type pair) 450 //name.toString(); // null check 451 //type.equals(type); // null check 452 // fill in fields: 453 this.clazz = defClass; 454 this.name = name; 455 this.type = type; 456 this.flags = flags; 457 assert(testAnyFlags(ALL_KINDS)); 458 assert(this.resolution == null); // nobody should have touched this yet 459 //assert(referenceKindIsConsistent()); // do this after resolution 460 } 461 462 private void expandFromVM() { 463 if (!isResolved()) return; 464 if (type instanceof Object[]) 465 type = null; // don't saddle JVM w/ typeInfo 466 MethodHandleNatives.expand(this); 467 } 468 469 // Capturing information from the Core Reflection API: 470 private static int flagsMods(int flags, int mods, byte refKind) { 471 assert((flags & RECOGNIZED_MODIFIERS) == 0); 472 assert((mods & ~RECOGNIZED_MODIFIERS) == 0); 473 assert((refKind & ~MN_REFERENCE_KIND_MASK) == 0); 474 return flags | mods | (refKind << MN_REFERENCE_KIND_SHIFT); 475 } 476 /** Create a name for the given reflected method. The resulting name will be in a resolved state. */ 477 public MemberName(Method m) { 478 this(m, false); 479 } 480 @SuppressWarnings("LeakingThisInConstructor") 481 public MemberName(Method m, boolean wantSpecial) { 482 m.getClass(); // NPE check 483 // fill in vmtarget, vmindex while we have m in hand: 484 MethodHandleNatives.init(this, m); 485 assert(isResolved() && this.clazz != null); 486 this.name = m.getName(); 487 if (this.type == null) 488 this.type = new Object[] { m.getReturnType(), m.getParameterTypes() }; 489 if (wantSpecial) { 490 assert(!isAbstract()) : this; 491 if (getReferenceKind() == REF_invokeVirtual) 492 changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual); 493 else if (getReferenceKind() == REF_invokeInterface) 494 // invokeSpecial on a default method 495 changeReferenceKind(REF_invokeSpecial, REF_invokeInterface); 496 } 497 } 498 public MemberName asSpecial() { 499 switch (getReferenceKind()) { 500 case REF_invokeSpecial: return this; 501 case REF_invokeVirtual: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual); 502 case REF_invokeInterface: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeInterface); 503 case REF_newInvokeSpecial: return clone().changeReferenceKind(REF_invokeSpecial, REF_newInvokeSpecial); 504 } 505 throw new IllegalArgumentException(this.toString()); 506 } 507 public MemberName asConstructor() { 508 switch (getReferenceKind()) { 509 case REF_invokeSpecial: return clone().changeReferenceKind(REF_newInvokeSpecial, REF_invokeSpecial); 510 case REF_newInvokeSpecial: return this; 511 } 512 throw new IllegalArgumentException(this.toString()); 513 } 514 /** Create a name for the given reflected constructor. The resulting name will be in a resolved state. */ 515 @SuppressWarnings("LeakingThisInConstructor") 516 public MemberName(Constructor<?> ctor) { 517 ctor.getClass(); // NPE check 518 // fill in vmtarget, vmindex while we have ctor in hand: 519 MethodHandleNatives.init(this, ctor); 520 assert(isResolved() && this.clazz != null); 521 this.name = CONSTRUCTOR_NAME; 522 if (this.type == null) 523 this.type = new Object[] { void.class, ctor.getParameterTypes() }; 524 } 525 /** Create a name for the given reflected field. The resulting name will be in a resolved state. 526 */ 527 public MemberName(Field fld) { 528 this(fld, false); 529 } 530 @SuppressWarnings("LeakingThisInConstructor") 531 public MemberName(Field fld, boolean makeSetter) { 532 fld.getClass(); // NPE check 533 // fill in vmtarget, vmindex while we have fld in hand: 534 MethodHandleNatives.init(this, fld); 535 assert(isResolved() && this.clazz != null); 536 this.name = fld.getName(); 537 this.type = fld.getType(); 538 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField)); 539 byte refKind = this.getReferenceKind(); 540 assert(refKind == (isStatic() ? REF_getStatic : REF_getField)); 541 if (makeSetter) { 542 changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind); 543 } 544 } 545 public boolean isGetter() { 546 return MethodHandleNatives.refKindIsGetter(getReferenceKind()); 547 } 548 public boolean isSetter() { 549 return MethodHandleNatives.refKindIsSetter(getReferenceKind()); 550 } 551 public MemberName asSetter() { 552 byte refKind = getReferenceKind(); 553 assert(MethodHandleNatives.refKindIsGetter(refKind)); 554 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField)); 555 byte setterRefKind = (byte)(refKind + (REF_putField - REF_getField)); 556 return clone().changeReferenceKind(setterRefKind, refKind); 557 } 558 /** Create a name for the given class. The resulting name will be in a resolved state. */ 559 public MemberName(Class<?> type) { 560 init(type.getDeclaringClass(), type.getSimpleName(), type, 561 flagsMods(IS_TYPE, type.getModifiers(), REF_NONE)); 562 initResolved(true); 563 } 564 565 // bare-bones constructor; the JVM will fill it in 566 MemberName() { } 567 568 // locally useful cloner 569 @Override protected MemberName clone() { 570 try { 571 return (MemberName) super.clone(); 572 } catch (CloneNotSupportedException ex) { 573 throw newInternalError(ex); 574 } 575 } 576 577 /** Get the definition of this member name. 578 * This may be in a super-class of the declaring class of this member. 579 */ 580 public MemberName getDefinition() { 581 if (!isResolved()) throw new IllegalStateException("must be resolved: "+this); 582 if (isType()) return this; 583 MemberName res = this.clone(); 584 res.clazz = null; 585 res.type = null; 586 res.name = null; 587 res.resolution = res; 588 res.expandFromVM(); 589 assert(res.getName().equals(this.getName())); 590 return res; 591 } 592 593 @Override 594 public int hashCode() { 595 return Objects.hash(clazz, flags, name, getType()); 596 } 597 @Override 598 public boolean equals(Object that) { 599 return (that instanceof MemberName && this.equals((MemberName)that)); 600 } 601 602 /** Decide if two member names have exactly the same symbolic content. 603 * Does not take into account any actual class members, so even if 604 * two member names resolve to the same actual member, they may 605 * be distinct references. 606 */ 607 public boolean equals(MemberName that) { 608 if (this == that) return true; 609 if (that == null) return false; 610 return this.clazz == that.clazz 611 && this.flags == that.flags 612 && Objects.equals(this.name, that.name) 613 && Objects.equals(this.getType(), that.getType()); 614 } 615 616 // Construction from symbolic parts, for queries: 617 /** Create a field or type name from the given components: Declaring class, name, type, reference kind. 618 * The declaring class may be supplied as null if this is to be a bare name and type. 619 * The resulting name will in an unresolved state. 620 */ 621 public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) { 622 init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind)); 623 initResolved(false); 624 } 625 /** Create a field or type name from the given components: Declaring class, name, type. 626 * The declaring class may be supplied as null if this is to be a bare name and type. 627 * The modifier flags default to zero. 628 * The resulting name will in an unresolved state. 629 */ 630 public MemberName(Class<?> defClass, String name, Class<?> type, Void unused) { 631 this(defClass, name, type, REF_NONE); 632 initResolved(false); 633 } 634 /** Create a method or constructor name from the given components: Declaring class, name, type, modifiers. 635 * It will be a constructor if and only if the name is {@code "<init>"}. 636 * The declaring class may be supplied as null if this is to be a bare name and type. 637 * The last argument is optional, a boolean which requests REF_invokeSpecial. 638 * The resulting name will in an unresolved state. 639 */ 640 public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) { 641 @SuppressWarnings("LocalVariableHidesMemberVariable") 642 int flags = (name != null && name.equals(CONSTRUCTOR_NAME) ? IS_CONSTRUCTOR : IS_METHOD); 643 init(defClass, name, type, flagsMods(flags, 0, refKind)); 644 initResolved(false); 645 } 646 // /** Create a method or constructor name from the given components: Declaring class, name, type, modifiers. 647 // * It will be a constructor if and only if the name is {@code "<init>"}. 648 // * The declaring class may be supplied as null if this is to be a bare name and type. 649 // * The modifier flags default to zero. 650 // * The resulting name will in an unresolved state. 651 // */ 652 // public MemberName(Class<?> defClass, String name, MethodType type, Void unused) { 653 // this(defClass, name, type, REF_NONE); 654 // } 655 656 /** Query whether this member name is resolved to a non-static, non-final method. 657 */ 658 public boolean hasReceiverTypeDispatch() { 659 return MethodHandleNatives.refKindDoesDispatch(getReferenceKind()); 660 } 661 662 /** Query whether this member name is resolved. 663 * A resolved member name is one for which the JVM has found 664 * a method, constructor, field, or type binding corresponding exactly to the name. 665 * (Document?) 666 */ 667 public boolean isResolved() { 668 return resolution == null; 669 } 670 671 private void initResolved(boolean isResolved) { 672 assert(this.resolution == null); // not initialized yet! 673 if (!isResolved) 674 this.resolution = this; 675 assert(isResolved() == isResolved); 676 } 677 678 void checkForTypeAlias() { 679 if (isInvocable()) { 680 MethodType type; 681 if (this.type instanceof MethodType) 682 type = (MethodType) this.type; 683 else 684 this.type = type = getMethodType(); 685 if (type.erase() == type) return; 686 if (VerifyAccess.isTypeVisible(type, clazz)) return; 687 throw new LinkageError("bad method type alias: "+type+" not visible from "+clazz); 688 } else { 689 Class<?> type; 690 if (this.type instanceof Class<?>) 691 type = (Class<?>) this.type; 692 else 693 this.type = type = getFieldType(); 694 if (VerifyAccess.isTypeVisible(type, clazz)) return; 695 throw new LinkageError("bad field type alias: "+type+" not visible from "+clazz); 696 } 697 } 698 699 700 /** Produce a string form of this member name. 701 * For types, it is simply the type's own string (as reported by {@code toString}). 702 * For fields, it is {@code "DeclaringClass.name/type"}. 703 * For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}. 704 * If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted. 705 * If the member is unresolved, a prefix {@code "*."} is prepended. 706 */ 707 @SuppressWarnings("LocalVariableHidesMemberVariable") 708 @Override 709 public String toString() { 710 if (isType()) 711 return type.toString(); // class java.lang.String 712 // else it is a field, method, or constructor 713 StringBuilder buf = new StringBuilder(); 714 if (getDeclaringClass() != null) { 715 buf.append(getName(clazz)); 716 buf.append('.'); 717 } 718 String name = getName(); 719 buf.append(name == null ? "*" : name); 720 Object type = getType(); 721 if (!isInvocable()) { 722 buf.append('/'); 723 buf.append(type == null ? "*" : getName(type)); 724 } else { 725 buf.append(type == null ? "(*)*" : getName(type)); 726 } 727 byte refKind = getReferenceKind(); 728 if (refKind != REF_NONE) { 729 buf.append('/'); 730 buf.append(MethodHandleNatives.refKindName(refKind)); 731 } 732 //buf.append("#").append(System.identityHashCode(this)); 733 return buf.toString(); 734 } 735 private static String getName(Object obj) { 736 if (obj instanceof Class<?>) 737 return ((Class<?>)obj).getName(); 738 return String.valueOf(obj); 739 } 740 741 public IllegalAccessException makeAccessException(String message, Object from) { 742 message = message + ": "+ toString(); 743 if (from != null) message += ", from " + from; 744 return new IllegalAccessException(message); 745 } 746 private String message() { 747 if (isResolved()) 748 return "no access"; 749 else if (isConstructor()) 750 return "no such constructor"; 751 else if (isMethod()) 752 return "no such method"; 753 else 754 return "no such field"; 755 } 756 public ReflectiveOperationException makeAccessException() { 757 String message = message() + ": "+ toString(); 758 ReflectiveOperationException ex; 759 if (isResolved() || !(resolution instanceof NoSuchMethodError || 760 resolution instanceof NoSuchFieldError)) 761 ex = new IllegalAccessException(message); 762 else if (isConstructor()) 763 ex = new NoSuchMethodException(message); 764 else if (isMethod()) 765 ex = new NoSuchMethodException(message); 766 else 767 ex = new NoSuchFieldException(message); 768 if (resolution instanceof Throwable) 769 ex.initCause((Throwable) resolution); 770 return ex; 771 } 772 773 /** Actually making a query requires an access check. */ 774 /*non-public*/ static Factory getFactory() { 775 return Factory.INSTANCE; 776 } 777 /** A factory type for resolving member names with the help of the VM. 778 * TBD: Define access-safe public constructors for this factory. 779 */ 780 /*non-public*/ static class Factory { 781 private Factory() { } // singleton pattern 782 static Factory INSTANCE = new Factory(); 783 784 private static int ALLOWED_FLAGS = ALL_KINDS; 785 786 /// Queries 787 List<MemberName> getMembers(Class<?> defc, 788 String matchName, Object matchType, 789 int matchFlags, Class<?> lookupClass) { 790 matchFlags &= ALLOWED_FLAGS; 791 String matchSig = null; 792 if (matchType != null) { 793 matchSig = BytecodeDescriptor.unparse(matchType); 794 if (matchSig.startsWith("(")) 795 matchFlags &= ~(ALL_KINDS & ~IS_INVOCABLE); 796 else 797 matchFlags &= ~(ALL_KINDS & ~IS_FIELD); 798 } 799 final int BUF_MAX = 0x2000; 800 int len1 = matchName == null ? 10 : matchType == null ? 4 : 1; 801 MemberName[] buf = newMemberBuffer(len1); 802 int totalCount = 0; 803 ArrayList<MemberName[]> bufs = null; 804 int bufCount = 0; 805 for (;;) { 806 bufCount = MethodHandleNatives.getMembers(defc, 807 matchName, matchSig, matchFlags, 808 lookupClass, 809 totalCount, buf); 810 if (bufCount <= buf.length) { 811 if (bufCount < 0) bufCount = 0; 812 totalCount += bufCount; 813 break; 814 } 815 // JVM returned to us with an intentional overflow! 816 totalCount += buf.length; 817 int excess = bufCount - buf.length; 818 if (bufs == null) bufs = new ArrayList<>(1); 819 bufs.add(buf); 820 int len2 = buf.length; 821 len2 = Math.max(len2, excess); 822 len2 = Math.max(len2, totalCount / 4); 823 buf = newMemberBuffer(Math.min(BUF_MAX, len2)); 824 } 825 ArrayList<MemberName> result = new ArrayList<>(totalCount); 826 if (bufs != null) { 827 for (MemberName[] buf0 : bufs) { 828 Collections.addAll(result, buf0); 829 } 830 } 831 result.addAll(Arrays.asList(buf).subList(0, bufCount)); 832 // Signature matching is not the same as type matching, since 833 // one signature might correspond to several types. 834 // So if matchType is a Class or MethodType, refilter the results. 835 if (matchType != null && matchType != matchSig) { 836 for (Iterator<MemberName> it = result.iterator(); it.hasNext();) { 837 MemberName m = it.next(); 838 if (!matchType.equals(m.getType())) 839 it.remove(); 840 } 841 } 842 return result; 843 } 844 /** Produce a resolved version of the given member. 845 * Super types are searched (for inherited members) if {@code searchSupers} is true. 846 * Access checking is performed on behalf of the given {@code lookupClass}. 847 * If lookup fails or access is not permitted, null is returned. 848 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 849 */ 850 private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass) { 851 MemberName m = ref.clone(); // JVM will side-effect the ref 852 assert(refKind == m.getReferenceKind()); 853 try { 854 m = MethodHandleNatives.resolve(m, lookupClass); 855 m.checkForTypeAlias(); 856 m.resolution = null; 857 } catch (LinkageError ex) { 858 // JVM reports that the "bytecode behavior" would get an error 859 assert(!m.isResolved()); 860 m.resolution = ex; 861 return m; 862 } 863 assert(m.referenceKindIsConsistent()); 864 m.initResolved(true); 865 assert(m.vminfoIsConsistent()); 866 return m; 867 } 868 /** Produce a resolved version of the given member. 869 * Super types are searched (for inherited members) if {@code searchSupers} is true. 870 * Access checking is performed on behalf of the given {@code lookupClass}. 871 * If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown. 872 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 873 */ 874 public 875 <NoSuchMemberException extends ReflectiveOperationException> 876 MemberName resolveOrFail(byte refKind, MemberName m, Class<?> lookupClass, 877 Class<NoSuchMemberException> nsmClass) 878 throws IllegalAccessException, NoSuchMemberException { 879 MemberName result = resolve(refKind, m, lookupClass); 880 if (result.isResolved()) 881 return result; 882 ReflectiveOperationException ex = result.makeAccessException(); 883 if (ex instanceof IllegalAccessException) throw (IllegalAccessException) ex; 884 throw nsmClass.cast(ex); 885 } 886 /** Produce a resolved version of the given member. 887 * Super types are searched (for inherited members) if {@code searchSupers} is true. 888 * Access checking is performed on behalf of the given {@code lookupClass}. 889 * If lookup fails or access is not permitted, return null. 890 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 891 */ 892 public 893 MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass) { 894 MemberName result = resolve(refKind, m, lookupClass); 895 if (result.isResolved()) 896 return result; 897 return null; 898 } 899 /** Return a list of all methods defined by the given class. 900 * Super types are searched (for inherited members) if {@code searchSupers} is true. 901 * Access checking is performed on behalf of the given {@code lookupClass}. 902 * Inaccessible members are not added to the last. 903 */ 904 public List<MemberName> getMethods(Class<?> defc, boolean searchSupers, 905 Class<?> lookupClass) { 906 return getMethods(defc, searchSupers, null, null, lookupClass); 907 } 908 /** Return a list of matching methods defined by the given class. 909 * Super types are searched (for inherited members) if {@code searchSupers} is true. 910 * Returned methods will match the name (if not null) and the type (if not null). 911 * Access checking is performed on behalf of the given {@code lookupClass}. 912 * Inaccessible members are not added to the last. 913 */ 914 public List<MemberName> getMethods(Class<?> defc, boolean searchSupers, 915 String name, MethodType type, Class<?> lookupClass) { 916 int matchFlags = IS_METHOD | (searchSupers ? SEARCH_ALL_SUPERS : 0); 917 return getMembers(defc, name, type, matchFlags, lookupClass); 918 } 919 /** Return a list of all constructors defined by the given class. 920 * Access checking is performed on behalf of the given {@code lookupClass}. 921 * Inaccessible members are not added to the last. 922 */ 923 public List<MemberName> getConstructors(Class<?> defc, Class<?> lookupClass) { 924 return getMembers(defc, null, null, IS_CONSTRUCTOR, lookupClass); 925 } 926 /** Return a list of all fields defined by the given class. 927 * Super types are searched (for inherited members) if {@code searchSupers} is true. 928 * Access checking is performed on behalf of the given {@code lookupClass}. 929 * Inaccessible members are not added to the last. 930 */ 931 public List<MemberName> getFields(Class<?> defc, boolean searchSupers, 932 Class<?> lookupClass) { 933 return getFields(defc, searchSupers, null, null, lookupClass); 934 } 935 /** Return a list of all fields defined by the given class. 936 * Super types are searched (for inherited members) if {@code searchSupers} is true. 937 * Returned fields will match the name (if not null) and the type (if not null). 938 * Access checking is performed on behalf of the given {@code lookupClass}. 939 * Inaccessible members are not added to the last. 940 */ 941 public List<MemberName> getFields(Class<?> defc, boolean searchSupers, 942 String name, Class<?> type, Class<?> lookupClass) { 943 int matchFlags = IS_FIELD | (searchSupers ? SEARCH_ALL_SUPERS : 0); 944 return getMembers(defc, name, type, matchFlags, lookupClass); 945 } 946 /** Return a list of all nested types defined by the given class. 947 * Super types are searched (for inherited members) if {@code searchSupers} is true. 948 * Access checking is performed on behalf of the given {@code lookupClass}. 949 * Inaccessible members are not added to the last. 950 */ 951 public List<MemberName> getNestedTypes(Class<?> defc, boolean searchSupers, 952 Class<?> lookupClass) { 953 int matchFlags = IS_TYPE | (searchSupers ? SEARCH_ALL_SUPERS : 0); 954 return getMembers(defc, null, null, matchFlags, lookupClass); 955 } 956 private static MemberName[] newMemberBuffer(int length) { 957 MemberName[] buf = new MemberName[length]; 958 // fill the buffer with dummy structs for the JVM to fill in 959 for (int i = 0; i < length; i++) 960 buf[i] = new MemberName(); 961 return buf; 962 } 963 } 964 965 // static { 966 // System.out.println("Hello world! My methods are:"); 967 // System.out.println(Factory.INSTANCE.getMethods(MemberName.class, true, null)); 968 // } 969 }