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 = MH_INVOKE_MODS; 324 final int negs = Modifier.STATIC; 325 if (testFlags(bits | negs, bits) && 326 clazz == MethodHandle.class) { 327 return isMethodHandleInvokeName(name); 328 } 329 return false; 330 } 331 public static boolean isMethodHandleInvokeName(String name) { 332 return name.equals("invoke") || name.equals("invokeExact"); 333 } 334 private static final int MH_INVOKE_MODS = Modifier.NATIVE | Modifier.FINAL | Modifier.PUBLIC; 335 336 /** Utility method to query the modifier flags of this member. */ 337 public boolean isStatic() { 338 return Modifier.isStatic(flags); 339 } 340 /** Utility method to query the modifier flags of this member. */ 341 public boolean isPublic() { 342 return Modifier.isPublic(flags); 343 } 344 /** Utility method to query the modifier flags of this member. */ 345 public boolean isPrivate() { 346 return Modifier.isPrivate(flags); 347 } 348 /** Utility method to query the modifier flags of this member. */ 349 public boolean isProtected() { 350 return Modifier.isProtected(flags); 351 } 352 /** Utility method to query the modifier flags of this member. */ 353 public boolean isFinal() { 354 return Modifier.isFinal(flags); 355 } 356 /** Utility method to query whether this member or its defining class is final. */ 357 public boolean canBeStaticallyBound() { 358 return Modifier.isFinal(flags | clazz.getModifiers()); 359 } 360 /** Utility method to query the modifier flags of this member. */ 361 public boolean isVolatile() { 362 return Modifier.isVolatile(flags); 363 } 364 /** Utility method to query the modifier flags of this member. */ 365 public boolean isAbstract() { 366 return Modifier.isAbstract(flags); 367 } 368 /** Utility method to query the modifier flags of this member. */ 369 public boolean isNative() { 370 return Modifier.isNative(flags); 371 } 372 // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo 373 374 // unofficial modifier flags, used by HotSpot: 375 static final int BRIDGE = 0x00000040; 376 static final int VARARGS = 0x00000080; 377 static final int SYNTHETIC = 0x00001000; 378 static final int ANNOTATION= 0x00002000; 379 static final int ENUM = 0x00004000; 380 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 381 public boolean isBridge() { 382 return testAllFlags(IS_METHOD | BRIDGE); 383 } 384 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 385 public boolean isVarargs() { 386 return testAllFlags(VARARGS) && isInvocable(); 387 } 388 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */ 389 public boolean isSynthetic() { 390 return testAllFlags(SYNTHETIC); 391 } 392 393 static final String CONSTRUCTOR_NAME = "<init>"; // the ever-popular 394 395 // modifiers exported by the JVM: 396 static final int RECOGNIZED_MODIFIERS = 0xFFFF; 397 398 // private flags, not part of RECOGNIZED_MODIFIERS: 399 static final int 400 IS_METHOD = MN_IS_METHOD, // method (not constructor) 401 IS_CONSTRUCTOR = MN_IS_CONSTRUCTOR, // constructor 402 IS_FIELD = MN_IS_FIELD, // field 403 IS_TYPE = MN_IS_TYPE, // nested type 404 CALLER_SENSITIVE = MN_CALLER_SENSITIVE; // @CallerSensitive annotation detected 405 406 static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; 407 static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE; 408 static final int IS_INVOCABLE = IS_METHOD | IS_CONSTRUCTOR; 409 static final int IS_FIELD_OR_METHOD = IS_METHOD | IS_FIELD; 410 static final int SEARCH_ALL_SUPERS = MN_SEARCH_SUPERCLASSES | MN_SEARCH_INTERFACES; 411 412 /** Utility method to query whether this member is a method or constructor. */ 413 public boolean isInvocable() { 414 return testAnyFlags(IS_INVOCABLE); 415 } 416 /** Utility method to query whether this member is a method, constructor, or field. */ 417 public boolean isFieldOrMethod() { 418 return testAnyFlags(IS_FIELD_OR_METHOD); 419 } 420 /** Query whether this member is a method. */ 421 public boolean isMethod() { 422 return testAllFlags(IS_METHOD); 423 } 424 /** Query whether this member is a constructor. */ 425 public boolean isConstructor() { 426 return testAllFlags(IS_CONSTRUCTOR); 427 } 428 /** Query whether this member is a field. */ 429 public boolean isField() { 430 return testAllFlags(IS_FIELD); 431 } 432 /** Query whether this member is a type. */ 433 public boolean isType() { 434 return testAllFlags(IS_TYPE); 435 } 436 /** Utility method to query whether this member is neither public, private, nor protected. */ 437 public boolean isPackage() { 438 return !testAnyFlags(ALL_ACCESS); 439 } 440 /** Query whether this member has a CallerSensitive annotation. */ 441 public boolean isCallerSensitive() { 442 return testAllFlags(CALLER_SENSITIVE); 443 } 444 445 /** Utility method to query whether this member is accessible from a given lookup class. */ 446 public boolean isAccessibleFrom(Class<?> lookupClass) { 447 return VerifyAccess.isMemberAccessible(this.getDeclaringClass(), this.getDeclaringClass(), flags, 448 lookupClass, ALL_ACCESS|MethodHandles.Lookup.PACKAGE); 449 } 450 451 /** Initialize a query. It is not resolved. */ 452 private void init(Class<?> defClass, String name, Object type, int flags) { 453 // defining class is allowed to be null (for a naked name/type pair) 454 //name.toString(); // null check 455 //type.equals(type); // null check 456 // fill in fields: 457 this.clazz = defClass; 458 this.name = name; 459 this.type = type; 460 this.flags = flags; 461 assert(testAnyFlags(ALL_KINDS)); 462 assert(this.resolution == null); // nobody should have touched this yet 463 //assert(referenceKindIsConsistent()); // do this after resolution 464 } 465 466 private void expandFromVM() { 467 if (!isResolved()) return; 468 if (type instanceof Object[]) 469 type = null; // don't saddle JVM w/ typeInfo 470 MethodHandleNatives.expand(this); 471 } 472 473 // Capturing information from the Core Reflection API: 474 private static int flagsMods(int flags, int mods, byte refKind) { 475 assert((flags & RECOGNIZED_MODIFIERS) == 0); 476 assert((mods & ~RECOGNIZED_MODIFIERS) == 0); 477 assert((refKind & ~MN_REFERENCE_KIND_MASK) == 0); 478 return flags | mods | (refKind << MN_REFERENCE_KIND_SHIFT); 479 } 480 /** Create a name for the given reflected method. The resulting name will be in a resolved state. */ 481 public MemberName(Method m) { 482 this(m, false); 483 } 484 @SuppressWarnings("LeakingThisInConstructor") 485 public MemberName(Method m, boolean wantSpecial) { 486 m.getClass(); // NPE check 487 // fill in vmtarget, vmindex while we have m in hand: 488 MethodHandleNatives.init(this, m); 489 if (clazz == null) { // MHN.init failed 490 if (m.getDeclaringClass() == MethodHandle.class && 491 isMethodHandleInvokeName(m.getName())) { 492 // The JVM did not reify this signature-polymorphic instance. 493 // Need a special case here. 494 // See comments on MethodHandleNatives.linkMethod. 495 MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes()); 496 int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual); 497 init(MethodHandle.class, m.getName(), type, flags); 498 if (isMethodHandleInvoke()) 499 return; 500 } 501 throw new LinkageError(m.toString()); 502 } 503 assert(isResolved() && this.clazz != null); 504 this.name = m.getName(); 505 if (this.type == null) 506 this.type = new Object[] { m.getReturnType(), m.getParameterTypes() }; 507 if (wantSpecial) { 508 if (isAbstract()) 509 throw new AbstractMethodError(this.toString()); 510 if (getReferenceKind() == REF_invokeVirtual) 511 changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual); 512 else if (getReferenceKind() == REF_invokeInterface) 513 // invokeSpecial on a default method 514 changeReferenceKind(REF_invokeSpecial, REF_invokeInterface); 515 } 516 } 517 public MemberName asSpecial() { 518 switch (getReferenceKind()) { 519 case REF_invokeSpecial: return this; 520 case REF_invokeVirtual: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual); 521 case REF_invokeInterface: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeInterface); 522 case REF_newInvokeSpecial: return clone().changeReferenceKind(REF_invokeSpecial, REF_newInvokeSpecial); 523 } 524 throw new IllegalArgumentException(this.toString()); 525 } 526 public MemberName asConstructor() { 527 switch (getReferenceKind()) { 528 case REF_invokeSpecial: return clone().changeReferenceKind(REF_newInvokeSpecial, REF_invokeSpecial); 529 case REF_newInvokeSpecial: return this; 530 } 531 throw new IllegalArgumentException(this.toString()); 532 } 533 /** Create a name for the given reflected constructor. The resulting name will be in a resolved state. */ 534 @SuppressWarnings("LeakingThisInConstructor") 535 public MemberName(Constructor<?> ctor) { 536 ctor.getClass(); // NPE check 537 // fill in vmtarget, vmindex while we have ctor in hand: 538 MethodHandleNatives.init(this, ctor); 539 assert(isResolved() && this.clazz != null); 540 this.name = CONSTRUCTOR_NAME; 541 if (this.type == null) 542 this.type = new Object[] { void.class, ctor.getParameterTypes() }; 543 } 544 /** Create a name for the given reflected field. The resulting name will be in a resolved state. 545 */ 546 public MemberName(Field fld) { 547 this(fld, false); 548 } 549 @SuppressWarnings("LeakingThisInConstructor") 550 public MemberName(Field fld, boolean makeSetter) { 551 fld.getClass(); // NPE check 552 // fill in vmtarget, vmindex while we have fld in hand: 553 MethodHandleNatives.init(this, fld); 554 assert(isResolved() && this.clazz != null); 555 this.name = fld.getName(); 556 this.type = fld.getType(); 557 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField)); 558 byte refKind = this.getReferenceKind(); 559 assert(refKind == (isStatic() ? REF_getStatic : REF_getField)); 560 if (makeSetter) { 561 changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind); 562 } 563 } 564 public boolean isGetter() { 565 return MethodHandleNatives.refKindIsGetter(getReferenceKind()); 566 } 567 public boolean isSetter() { 568 return MethodHandleNatives.refKindIsSetter(getReferenceKind()); 569 } 570 public MemberName asSetter() { 571 byte refKind = getReferenceKind(); 572 assert(MethodHandleNatives.refKindIsGetter(refKind)); 573 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField)); 574 byte setterRefKind = (byte)(refKind + (REF_putField - REF_getField)); 575 return clone().changeReferenceKind(setterRefKind, refKind); 576 } 577 /** Create a name for the given class. The resulting name will be in a resolved state. */ 578 public MemberName(Class<?> type) { 579 init(type.getDeclaringClass(), type.getSimpleName(), type, 580 flagsMods(IS_TYPE, type.getModifiers(), REF_NONE)); 581 initResolved(true); 582 } 583 584 /** 585 * Create a name for a signature-polymorphic invoker. 586 * This is a placeholder for a signature-polymorphic instance 587 * (of MH.invokeExact, etc.) that the JVM does not reify. 588 * See comments on {@link MethodHandleNatives#linkMethod}. 589 */ 590 static MemberName makeMethodHandleInvoke(String name, MethodType type) { 591 return makeMethodHandleInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC); 592 } 593 static MemberName makeMethodHandleInvoke(String name, MethodType type, int mods) { 594 MemberName mem = new MemberName(MethodHandle.class, name, type, REF_invokeVirtual); 595 mem.flags |= mods; // it's not resolved, but add these modifiers anyway 596 assert(mem.isMethodHandleInvoke()) : mem; 597 return mem; 598 } 599 600 // bare-bones constructor; the JVM will fill it in 601 MemberName() { } 602 603 // locally useful cloner 604 @Override protected MemberName clone() { 605 try { 606 return (MemberName) super.clone(); 607 } catch (CloneNotSupportedException ex) { 608 throw newInternalError(ex); 609 } 610 } 611 612 /** Get the definition of this member name. 613 * This may be in a super-class of the declaring class of this member. 614 */ 615 public MemberName getDefinition() { 616 if (!isResolved()) throw new IllegalStateException("must be resolved: "+this); 617 if (isType()) return this; 618 MemberName res = this.clone(); 619 res.clazz = null; 620 res.type = null; 621 res.name = null; 622 res.resolution = res; 623 res.expandFromVM(); 624 assert(res.getName().equals(this.getName())); 625 return res; 626 } 627 628 @Override 629 public int hashCode() { 630 return Objects.hash(clazz, flags, name, getType()); 631 } 632 @Override 633 public boolean equals(Object that) { 634 return (that instanceof MemberName && this.equals((MemberName)that)); 635 } 636 637 /** Decide if two member names have exactly the same symbolic content. 638 * Does not take into account any actual class members, so even if 639 * two member names resolve to the same actual member, they may 640 * be distinct references. 641 */ 642 public boolean equals(MemberName that) { 643 if (this == that) return true; 644 if (that == null) return false; 645 return this.clazz == that.clazz 646 && this.flags == that.flags 647 && Objects.equals(this.name, that.name) 648 && Objects.equals(this.getType(), that.getType()); 649 } 650 651 // Construction from symbolic parts, for queries: 652 /** Create a field or type name from the given components: Declaring class, name, type, reference kind. 653 * The declaring class may be supplied as null if this is to be a bare name and type. 654 * The resulting name will in an unresolved state. 655 */ 656 public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) { 657 init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind)); 658 initResolved(false); 659 } 660 /** Create a field or type name from the given components: Declaring class, name, type. 661 * The declaring class may be supplied as null if this is to be a bare name and type. 662 * The modifier flags default to zero. 663 * The resulting name will in an unresolved state. 664 */ 665 public MemberName(Class<?> defClass, String name, Class<?> type, Void unused) { 666 this(defClass, name, type, REF_NONE); 667 initResolved(false); 668 } 669 /** Create a method or constructor name from the given components: Declaring class, name, type, modifiers. 670 * It will be a constructor if and only if the name is {@code "<init>"}. 671 * The declaring class may be supplied as null if this is to be a bare name and type. 672 * The last argument is optional, a boolean which requests REF_invokeSpecial. 673 * The resulting name will in an unresolved state. 674 */ 675 public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) { 676 @SuppressWarnings("LocalVariableHidesMemberVariable") 677 int flags = (name != null && name.equals(CONSTRUCTOR_NAME) ? IS_CONSTRUCTOR : IS_METHOD); 678 init(defClass, name, type, flagsMods(flags, 0, refKind)); 679 initResolved(false); 680 } 681 // /** Create a method or constructor name from the given components: Declaring class, name, type, modifiers. 682 // * It will be a constructor if and only if the name is {@code "<init>"}. 683 // * The declaring class may be supplied as null if this is to be a bare name and type. 684 // * The modifier flags default to zero. 685 // * The resulting name will in an unresolved state. 686 // */ 687 // public MemberName(Class<?> defClass, String name, MethodType type, Void unused) { 688 // this(defClass, name, type, REF_NONE); 689 // } 690 691 /** Query whether this member name is resolved to a non-static, non-final method. 692 */ 693 public boolean hasReceiverTypeDispatch() { 694 return MethodHandleNatives.refKindDoesDispatch(getReferenceKind()); 695 } 696 697 /** Query whether this member name is resolved. 698 * A resolved member name is one for which the JVM has found 699 * a method, constructor, field, or type binding corresponding exactly to the name. 700 * (Document?) 701 */ 702 public boolean isResolved() { 703 return resolution == null; 704 } 705 706 private void initResolved(boolean isResolved) { 707 assert(this.resolution == null); // not initialized yet! 708 if (!isResolved) 709 this.resolution = this; 710 assert(isResolved() == isResolved); 711 } 712 713 void checkForTypeAlias() { 714 if (isInvocable()) { 715 MethodType type; 716 if (this.type instanceof MethodType) 717 type = (MethodType) this.type; 718 else 719 this.type = type = getMethodType(); 720 if (type.erase() == type) return; 721 if (VerifyAccess.isTypeVisible(type, clazz)) return; 722 throw new LinkageError("bad method type alias: "+type+" not visible from "+clazz); 723 } else { 724 Class<?> type; 725 if (this.type instanceof Class<?>) 726 type = (Class<?>) this.type; 727 else 728 this.type = type = getFieldType(); 729 if (VerifyAccess.isTypeVisible(type, clazz)) return; 730 throw new LinkageError("bad field type alias: "+type+" not visible from "+clazz); 731 } 732 } 733 734 735 /** Produce a string form of this member name. 736 * For types, it is simply the type's own string (as reported by {@code toString}). 737 * For fields, it is {@code "DeclaringClass.name/type"}. 738 * For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}. 739 * If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted. 740 * If the member is unresolved, a prefix {@code "*."} is prepended. 741 */ 742 @SuppressWarnings("LocalVariableHidesMemberVariable") 743 @Override 744 public String toString() { 745 if (isType()) 746 return type.toString(); // class java.lang.String 747 // else it is a field, method, or constructor 748 StringBuilder buf = new StringBuilder(); 749 if (getDeclaringClass() != null) { 750 buf.append(getName(clazz)); 751 buf.append('.'); 752 } 753 String name = getName(); 754 buf.append(name == null ? "*" : name); 755 Object type = getType(); 756 if (!isInvocable()) { 757 buf.append('/'); 758 buf.append(type == null ? "*" : getName(type)); 759 } else { 760 buf.append(type == null ? "(*)*" : getName(type)); 761 } 762 byte refKind = getReferenceKind(); 763 if (refKind != REF_NONE) { 764 buf.append('/'); 765 buf.append(MethodHandleNatives.refKindName(refKind)); 766 } 767 //buf.append("#").append(System.identityHashCode(this)); 768 return buf.toString(); 769 } 770 private static String getName(Object obj) { 771 if (obj instanceof Class<?>) 772 return ((Class<?>)obj).getName(); 773 return String.valueOf(obj); 774 } 775 776 public IllegalAccessException makeAccessException(String message, Object from) { 777 message = message + ": "+ toString(); 778 if (from != null) message += ", from " + from; 779 return new IllegalAccessException(message); 780 } 781 private String message() { 782 if (isResolved()) 783 return "no access"; 784 else if (isConstructor()) 785 return "no such constructor"; 786 else if (isMethod()) 787 return "no such method"; 788 else 789 return "no such field"; 790 } 791 public ReflectiveOperationException makeAccessException() { 792 String message = message() + ": "+ toString(); 793 ReflectiveOperationException ex; 794 if (isResolved() || !(resolution instanceof NoSuchMethodError || 795 resolution instanceof NoSuchFieldError)) 796 ex = new IllegalAccessException(message); 797 else if (isConstructor()) 798 ex = new NoSuchMethodException(message); 799 else if (isMethod()) 800 ex = new NoSuchMethodException(message); 801 else 802 ex = new NoSuchFieldException(message); 803 if (resolution instanceof Throwable) 804 ex.initCause((Throwable) resolution); 805 return ex; 806 } 807 808 /** Actually making a query requires an access check. */ 809 /*non-public*/ static Factory getFactory() { 810 return Factory.INSTANCE; 811 } 812 /** A factory type for resolving member names with the help of the VM. 813 * TBD: Define access-safe public constructors for this factory. 814 */ 815 /*non-public*/ static class Factory { 816 private Factory() { } // singleton pattern 817 static Factory INSTANCE = new Factory(); 818 819 private static int ALLOWED_FLAGS = ALL_KINDS; 820 821 /// Queries 822 List<MemberName> getMembers(Class<?> defc, 823 String matchName, Object matchType, 824 int matchFlags, Class<?> lookupClass) { 825 matchFlags &= ALLOWED_FLAGS; 826 String matchSig = null; 827 if (matchType != null) { 828 matchSig = BytecodeDescriptor.unparse(matchType); 829 if (matchSig.startsWith("(")) 830 matchFlags &= ~(ALL_KINDS & ~IS_INVOCABLE); 831 else 832 matchFlags &= ~(ALL_KINDS & ~IS_FIELD); 833 } 834 final int BUF_MAX = 0x2000; 835 int len1 = matchName == null ? 10 : matchType == null ? 4 : 1; 836 MemberName[] buf = newMemberBuffer(len1); 837 int totalCount = 0; 838 ArrayList<MemberName[]> bufs = null; 839 int bufCount = 0; 840 for (;;) { 841 bufCount = MethodHandleNatives.getMembers(defc, 842 matchName, matchSig, matchFlags, 843 lookupClass, 844 totalCount, buf); 845 if (bufCount <= buf.length) { 846 if (bufCount < 0) bufCount = 0; 847 totalCount += bufCount; 848 break; 849 } 850 // JVM returned to us with an intentional overflow! 851 totalCount += buf.length; 852 int excess = bufCount - buf.length; 853 if (bufs == null) bufs = new ArrayList<>(1); 854 bufs.add(buf); 855 int len2 = buf.length; 856 len2 = Math.max(len2, excess); 857 len2 = Math.max(len2, totalCount / 4); 858 buf = newMemberBuffer(Math.min(BUF_MAX, len2)); 859 } 860 ArrayList<MemberName> result = new ArrayList<>(totalCount); 861 if (bufs != null) { 862 for (MemberName[] buf0 : bufs) { 863 Collections.addAll(result, buf0); 864 } 865 } 866 result.addAll(Arrays.asList(buf).subList(0, bufCount)); 867 // Signature matching is not the same as type matching, since 868 // one signature might correspond to several types. 869 // So if matchType is a Class or MethodType, refilter the results. 870 if (matchType != null && matchType != matchSig) { 871 for (Iterator<MemberName> it = result.iterator(); it.hasNext();) { 872 MemberName m = it.next(); 873 if (!matchType.equals(m.getType())) 874 it.remove(); 875 } 876 } 877 return result; 878 } 879 /** Produce a resolved version of the given member. 880 * Super types are searched (for inherited members) if {@code searchSupers} is true. 881 * Access checking is performed on behalf of the given {@code lookupClass}. 882 * If lookup fails or access is not permitted, null is returned. 883 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 884 */ 885 private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass) { 886 MemberName m = ref.clone(); // JVM will side-effect the ref 887 assert(refKind == m.getReferenceKind()); 888 try { 889 m = MethodHandleNatives.resolve(m, lookupClass); 890 m.checkForTypeAlias(); 891 m.resolution = null; 892 } catch (LinkageError ex) { 893 // JVM reports that the "bytecode behavior" would get an error 894 assert(!m.isResolved()); 895 m.resolution = ex; 896 return m; 897 } 898 assert(m.referenceKindIsConsistent()); 899 m.initResolved(true); 900 assert(m.vminfoIsConsistent()); 901 return m; 902 } 903 /** Produce a resolved version of the given member. 904 * Super types are searched (for inherited members) if {@code searchSupers} is true. 905 * Access checking is performed on behalf of the given {@code lookupClass}. 906 * If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown. 907 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 908 */ 909 public 910 <NoSuchMemberException extends ReflectiveOperationException> 911 MemberName resolveOrFail(byte refKind, MemberName m, Class<?> lookupClass, 912 Class<NoSuchMemberException> nsmClass) 913 throws IllegalAccessException, NoSuchMemberException { 914 MemberName result = resolve(refKind, m, lookupClass); 915 if (result.isResolved()) 916 return result; 917 ReflectiveOperationException ex = result.makeAccessException(); 918 if (ex instanceof IllegalAccessException) throw (IllegalAccessException) ex; 919 throw nsmClass.cast(ex); 920 } 921 /** Produce a resolved version of the given member. 922 * Super types are searched (for inherited members) if {@code searchSupers} is true. 923 * Access checking is performed on behalf of the given {@code lookupClass}. 924 * If lookup fails or access is not permitted, return null. 925 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in. 926 */ 927 public 928 MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass) { 929 MemberName result = resolve(refKind, m, lookupClass); 930 if (result.isResolved()) 931 return result; 932 return null; 933 } 934 /** Return a list of all methods defined by the given class. 935 * Super types are searched (for inherited members) if {@code searchSupers} is true. 936 * Access checking is performed on behalf of the given {@code lookupClass}. 937 * Inaccessible members are not added to the last. 938 */ 939 public List<MemberName> getMethods(Class<?> defc, boolean searchSupers, 940 Class<?> lookupClass) { 941 return getMethods(defc, searchSupers, null, null, lookupClass); 942 } 943 /** Return a list of matching methods defined by the given class. 944 * Super types are searched (for inherited members) if {@code searchSupers} is true. 945 * Returned methods will match the name (if not null) and the type (if not null). 946 * Access checking is performed on behalf of the given {@code lookupClass}. 947 * Inaccessible members are not added to the last. 948 */ 949 public List<MemberName> getMethods(Class<?> defc, boolean searchSupers, 950 String name, MethodType type, Class<?> lookupClass) { 951 int matchFlags = IS_METHOD | (searchSupers ? SEARCH_ALL_SUPERS : 0); 952 return getMembers(defc, name, type, matchFlags, lookupClass); 953 } 954 /** Return a list of all constructors defined by the given class. 955 * Access checking is performed on behalf of the given {@code lookupClass}. 956 * Inaccessible members are not added to the last. 957 */ 958 public List<MemberName> getConstructors(Class<?> defc, Class<?> lookupClass) { 959 return getMembers(defc, null, null, IS_CONSTRUCTOR, lookupClass); 960 } 961 /** Return a list of all fields defined by the given class. 962 * Super types are searched (for inherited members) if {@code searchSupers} is true. 963 * Access checking is performed on behalf of the given {@code lookupClass}. 964 * Inaccessible members are not added to the last. 965 */ 966 public List<MemberName> getFields(Class<?> defc, boolean searchSupers, 967 Class<?> lookupClass) { 968 return getFields(defc, searchSupers, null, null, lookupClass); 969 } 970 /** Return a list of all fields defined by the given class. 971 * Super types are searched (for inherited members) if {@code searchSupers} is true. 972 * Returned fields will match the name (if not null) and the type (if not null). 973 * Access checking is performed on behalf of the given {@code lookupClass}. 974 * Inaccessible members are not added to the last. 975 */ 976 public List<MemberName> getFields(Class<?> defc, boolean searchSupers, 977 String name, Class<?> type, Class<?> lookupClass) { 978 int matchFlags = IS_FIELD | (searchSupers ? SEARCH_ALL_SUPERS : 0); 979 return getMembers(defc, name, type, matchFlags, lookupClass); 980 } 981 /** Return a list of all nested types defined by the given class. 982 * Super types are searched (for inherited members) if {@code searchSupers} is true. 983 * Access checking is performed on behalf of the given {@code lookupClass}. 984 * Inaccessible members are not added to the last. 985 */ 986 public List<MemberName> getNestedTypes(Class<?> defc, boolean searchSupers, 987 Class<?> lookupClass) { 988 int matchFlags = IS_TYPE | (searchSupers ? SEARCH_ALL_SUPERS : 0); 989 return getMembers(defc, null, null, matchFlags, lookupClass); 990 } 991 private static MemberName[] newMemberBuffer(int length) { 992 MemberName[] buf = new MemberName[length]; 993 // fill the buffer with dummy structs for the JVM to fill in 994 for (int i = 0; i < length; i++) 995 buf[i] = new MemberName(); 996 return buf; 997 } 998 } 999 1000 // static { 1001 // System.out.println("Hello world! My methods are:"); 1002 // System.out.println(Factory.INSTANCE.getMethods(MemberName.class, true, null)); 1003 // } 1004 }