Need to initialize flags. getFields throws SecurityException on bck2brwsr VM - avoid.
2 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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.
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).
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.
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
26 package java.lang.invoke;
28 import sun.invoke.util.BytecodeDescriptor;
29 import sun.invoke.util.VerifyAccess;
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;
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
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.
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.
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.
72 /*non-public*/ final class MemberName implements Member, Cloneable {
73 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 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
81 /** Return the declaring class of this member.
82 * In the case of a bare name and type, the declaring class will be null.
84 public Class<?> getDeclaringClass() {
88 /** Utility method producing the class loader of the declaring class. */
89 public ClassLoader getClassLoader() {
90 return clazz.getClassLoader();
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>"}.
98 public String getName() {
108 public MethodType getMethodOrFieldType() {
110 return getMethodType();
112 return MethodType.methodType(getFieldType());
114 return MethodType.methodType(void.class, getFieldType());
115 throw new InternalError("not a method or field: "+this);
118 /** Return the declared type of this member, which
119 * must be a method or constructor.
121 public MethodType getMethodType() {
128 if (!isInvocable()) {
129 throw newIllegalArgumentException("not invocable, no method type");
133 // Get a snapshot of type which doesn't get changed by racing threads.
134 final Object type = this.type;
135 if (type instanceof MethodType) {
136 return (MethodType) type;
140 // type is not a MethodType yet. Convert it thread-safely.
141 synchronized (this) {
142 if (type instanceof String) {
143 String sig = (String) type;
144 MethodType res = MethodType.fromMethodDescriptorString(sig, getClassLoader());
146 } else if (type instanceof Object[]) {
147 Object[] typeInfo = (Object[]) type;
148 Class<?>[] ptypes = (Class<?>[]) typeInfo[1];
149 Class<?> rtype = (Class<?>) typeInfo[0];
150 MethodType res = MethodType.methodType(rtype, ptypes);
153 // Make sure type is a MethodType for racing threads.
154 assert type instanceof MethodType : "bad method type " + type;
156 return (MethodType) type;
159 /** Return the actual type under which this method or constructor must be invoked.
160 * For non-static methods or constructors, this is the type with a leading parameter,
161 * a reference to declaring class. For static methods, it is the same as the declared type.
163 public MethodType getInvocationType() {
164 MethodType itype = getMethodOrFieldType();
165 if (isConstructor() && getReferenceKind() == REF_newInvokeSpecial)
166 return itype.changeReturnType(clazz);
168 return itype.insertParameterTypes(0, clazz);
172 /** Utility method producing the parameter types of the method type. */
173 public Class<?>[] getParameterTypes() {
174 return getMethodType().parameterArray();
177 /** Utility method producing the return type of the method type. */
178 public Class<?> getReturnType() {
179 return getMethodType().returnType();
182 /** Return the declared type of this member, which
183 * must be a field or type.
184 * If it is a type member, that type itself is returned.
186 public Class<?> getFieldType() {
194 throw newIllegalArgumentException("not a field or nested class, no simple type");
198 // Get a snapshot of type which doesn't get changed by racing threads.
199 final Object type = this.type;
200 if (type instanceof Class<?>) {
201 return (Class<?>) type;
205 // type is not a Class yet. Convert it thread-safely.
206 synchronized (this) {
207 if (type instanceof String) {
208 String sig = (String) type;
209 MethodType mtype = MethodType.fromMethodDescriptorString("()"+sig, getClassLoader());
210 Class<?> res = mtype.returnType();
213 // Make sure type is a Class for racing threads.
214 assert type instanceof Class<?> : "bad field type " + type;
216 return (Class<?>) type;
219 /** Utility method to produce either the method type or field type of this member. */
220 public Object getType() {
221 return (isInvocable() ? getMethodType() : getFieldType());
224 /** Utility method to produce the signature of this member,
225 * used within the class file format to describe its type.
227 public String getSignature() {
235 return BytecodeDescriptor.unparse(getMethodType());
237 return BytecodeDescriptor.unparse(getFieldType());
240 /** Return the modifier flags of this member.
241 * @see java.lang.reflect.Modifier
243 public int getModifiers() {
244 return (flags & RECOGNIZED_MODIFIERS);
247 /** Return the reference kind of this member, or zero if none.
249 public byte getReferenceKind() {
250 return (byte) ((flags >>> MN_REFERENCE_KIND_SHIFT) & MN_REFERENCE_KIND_MASK);
252 private boolean referenceKindIsConsistent() {
253 byte refKind = getReferenceKind();
254 if (refKind == REF_NONE) return isType();
256 assert(staticIsConsistent());
257 assert(MethodHandleNatives.refKindIsField(refKind));
258 } else if (isConstructor()) {
259 assert(refKind == REF_newInvokeSpecial || refKind == REF_invokeSpecial);
260 } else if (isMethod()) {
261 assert(staticIsConsistent());
262 assert(MethodHandleNatives.refKindIsMethod(refKind));
263 if (clazz.isInterface())
264 assert(refKind == REF_invokeInterface ||
265 refKind == REF_invokeStatic ||
266 refKind == REF_invokeSpecial ||
267 refKind == REF_invokeVirtual && isObjectPublicMethod());
273 private boolean isObjectPublicMethod() {
274 if (clazz == Object.class) return true;
275 MethodType mtype = getMethodType();
276 if (name.equals("toString") && mtype.returnType() == String.class && mtype.parameterCount() == 0)
278 if (name.equals("hashCode") && mtype.returnType() == int.class && mtype.parameterCount() == 0)
280 if (name.equals("equals") && mtype.returnType() == boolean.class && mtype.parameterCount() == 1 && mtype.parameterType(0) == Object.class)
284 /*non-public*/ boolean referenceKindIsConsistentWith(int originalRefKind) {
285 int refKind = getReferenceKind();
286 if (refKind == originalRefKind) return true;
287 switch (originalRefKind) {
288 case REF_invokeInterface:
289 // Looking up an interface method, can get (e.g.) Object.hashCode
290 assert(refKind == REF_invokeVirtual ||
291 refKind == REF_invokeSpecial) : this;
293 case REF_invokeVirtual:
294 case REF_newInvokeSpecial:
295 // Looked up a virtual, can get (e.g.) final String.hashCode.
296 assert(refKind == REF_invokeSpecial) : this;
299 assert(false) : this+" != "+MethodHandleNatives.refKindName((byte)originalRefKind);
302 private boolean staticIsConsistent() {
303 byte refKind = getReferenceKind();
304 return MethodHandleNatives.refKindIsStatic(refKind) == isStatic() || getModifiers() == 0;
306 private boolean vminfoIsConsistent() {
307 byte refKind = getReferenceKind();
308 assert(isResolved()); // else don't call
309 Object vminfo = MethodHandleNatives.getMemberVMInfo(this);
310 assert(vminfo instanceof Object[]);
311 long vmindex = (Long) ((Object[])vminfo)[0];
312 Object vmtarget = ((Object[])vminfo)[1];
313 if (MethodHandleNatives.refKindIsField(refKind)) {
314 assert(vmindex >= 0) : vmindex + ":" + this;
315 assert(vmtarget instanceof Class);
317 if (MethodHandleNatives.refKindDoesDispatch(refKind))
318 assert(vmindex >= 0) : vmindex + ":" + this;
320 assert(vmindex < 0) : vmindex;
321 assert(vmtarget instanceof MemberName) : vmtarget + " in " + this;
326 private MemberName changeReferenceKind(byte refKind, byte oldKind) {
327 assert(getReferenceKind() == oldKind);
328 assert(MethodHandleNatives.refKindIsValid(refKind));
329 flags += (((int)refKind - oldKind) << MN_REFERENCE_KIND_SHIFT);
330 // if (isConstructor() && refKind != REF_newInvokeSpecial)
331 // flags += (IS_METHOD - IS_CONSTRUCTOR);
332 // else if (refKind == REF_newInvokeSpecial && isMethod())
333 // flags += (IS_CONSTRUCTOR - IS_METHOD);
337 private boolean testFlags(int mask, int value) {
338 return (flags & mask) == value;
340 private boolean testAllFlags(int mask) {
341 return testFlags(mask, mask);
343 private boolean testAnyFlags(int mask) {
344 return !testFlags(mask, 0);
347 /** Utility method to query if this member is a method handle invocation (invoke or invokeExact). */
348 public boolean isMethodHandleInvoke() {
349 final int bits = MH_INVOKE_MODS;
350 final int negs = Modifier.STATIC;
351 if (testFlags(bits | negs, bits) &&
352 clazz == MethodHandle.class) {
353 return isMethodHandleInvokeName(name);
357 public static boolean isMethodHandleInvokeName(String name) {
358 return name.equals("invoke") || name.equals("invokeExact");
360 private static final int MH_INVOKE_MODS = Modifier.NATIVE | Modifier.FINAL | Modifier.PUBLIC;
362 /** Utility method to query the modifier flags of this member. */
363 public boolean isStatic() {
364 return Modifier.isStatic(flags);
366 /** Utility method to query the modifier flags of this member. */
367 public boolean isPublic() {
368 return Modifier.isPublic(flags);
370 /** Utility method to query the modifier flags of this member. */
371 public boolean isPrivate() {
372 return Modifier.isPrivate(flags);
374 /** Utility method to query the modifier flags of this member. */
375 public boolean isProtected() {
376 return Modifier.isProtected(flags);
378 /** Utility method to query the modifier flags of this member. */
379 public boolean isFinal() {
380 return Modifier.isFinal(flags);
382 /** Utility method to query whether this member or its defining class is final. */
383 public boolean canBeStaticallyBound() {
384 return Modifier.isFinal(flags | clazz.getModifiers());
386 /** Utility method to query the modifier flags of this member. */
387 public boolean isVolatile() {
388 return Modifier.isVolatile(flags);
390 /** Utility method to query the modifier flags of this member. */
391 public boolean isAbstract() {
392 return Modifier.isAbstract(flags);
394 /** Utility method to query the modifier flags of this member. */
395 public boolean isNative() {
396 return Modifier.isNative(flags);
398 // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo
400 // unofficial modifier flags, used by HotSpot:
401 static final int BRIDGE = 0x00000040;
402 static final int VARARGS = 0x00000080;
403 static final int SYNTHETIC = 0x00001000;
404 static final int ANNOTATION= 0x00002000;
405 static final int ENUM = 0x00004000;
406 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
407 public boolean isBridge() {
408 return testAllFlags(IS_METHOD | BRIDGE);
410 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
411 public boolean isVarargs() {
412 return testAllFlags(VARARGS) && isInvocable();
414 /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
415 public boolean isSynthetic() {
416 return testAllFlags(SYNTHETIC);
419 static final String CONSTRUCTOR_NAME = "<init>"; // the ever-popular
421 // modifiers exported by the JVM:
422 static final int RECOGNIZED_MODIFIERS = 0xFFFF;
424 // private flags, not part of RECOGNIZED_MODIFIERS:
426 IS_METHOD = MN_IS_METHOD, // method (not constructor)
427 IS_CONSTRUCTOR = MN_IS_CONSTRUCTOR, // constructor
428 IS_FIELD = MN_IS_FIELD, // field
429 IS_TYPE = MN_IS_TYPE, // nested type
430 CALLER_SENSITIVE = MN_CALLER_SENSITIVE; // @CallerSensitive annotation detected
432 static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
433 static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE;
434 static final int IS_INVOCABLE = IS_METHOD | IS_CONSTRUCTOR;
435 static final int IS_FIELD_OR_METHOD = IS_METHOD | IS_FIELD;
436 static final int SEARCH_ALL_SUPERS = MN_SEARCH_SUPERCLASSES | MN_SEARCH_INTERFACES;
438 /** Utility method to query whether this member is a method or constructor. */
439 public boolean isInvocable() {
440 return testAnyFlags(IS_INVOCABLE);
442 /** Utility method to query whether this member is a method, constructor, or field. */
443 public boolean isFieldOrMethod() {
444 return testAnyFlags(IS_FIELD_OR_METHOD);
446 /** Query whether this member is a method. */
447 public boolean isMethod() {
448 return testAllFlags(IS_METHOD);
450 /** Query whether this member is a constructor. */
451 public boolean isConstructor() {
452 return testAllFlags(IS_CONSTRUCTOR);
454 /** Query whether this member is a field. */
455 public boolean isField() {
456 return testAllFlags(IS_FIELD);
458 /** Query whether this member is a type. */
459 public boolean isType() {
460 return testAllFlags(IS_TYPE);
462 /** Utility method to query whether this member is neither public, private, nor protected. */
463 public boolean isPackage() {
464 return !testAnyFlags(ALL_ACCESS);
466 /** Query whether this member has a CallerSensitive annotation. */
467 public boolean isCallerSensitive() {
468 return testAllFlags(CALLER_SENSITIVE);
471 /** Utility method to query whether this member is accessible from a given lookup class. */
472 public boolean isAccessibleFrom(Class<?> lookupClass) {
473 return VerifyAccess.isMemberAccessible(this.getDeclaringClass(), this.getDeclaringClass(), flags,
474 lookupClass, ALL_ACCESS|MethodHandles.Lookup.PACKAGE);
477 /** Initialize a query. It is not resolved. */
478 private void init(Class<?> defClass, String name, Object type, int flags) {
479 // defining class is allowed to be null (for a naked name/type pair)
480 //name.toString(); // null check
481 //type.equals(type); // null check
483 this.clazz = defClass;
487 assert(testAnyFlags(ALL_KINDS));
488 assert(this.resolution == null); // nobody should have touched this yet
489 //assert(referenceKindIsConsistent()); // do this after resolution
493 * Calls down to the VM to fill in the fields. This method is
494 * synchronized to avoid racing calls.
496 private void expandFromVM() {
503 MethodHandleNatives.expand(this);
506 // Capturing information from the Core Reflection API:
507 private static int flagsMods(int flags, int mods, byte refKind) {
508 assert((flags & RECOGNIZED_MODIFIERS) == 0);
509 assert((mods & ~RECOGNIZED_MODIFIERS) == 0);
510 assert((refKind & ~MN_REFERENCE_KIND_MASK) == 0);
511 return flags | mods | (refKind << MN_REFERENCE_KIND_SHIFT);
513 /** Create a name for the given reflected method. The resulting name will be in a resolved state. */
514 public MemberName(Method m) {
517 @SuppressWarnings("LeakingThisInConstructor")
518 public MemberName(Method m, boolean wantSpecial) {
519 m.getClass(); // NPE check
520 // fill in vmtarget, vmindex while we have m in hand:
521 MethodHandleNatives.init(this, m);
522 if (clazz == null) { // MHN.init failed
523 if (m.getDeclaringClass() == MethodHandle.class &&
524 isMethodHandleInvokeName(m.getName())) {
525 // The JVM did not reify this signature-polymorphic instance.
526 // Need a special case here.
527 // See comments on MethodHandleNatives.linkMethod.
528 MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
529 int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
530 init(MethodHandle.class, m.getName(), type, flags);
531 if (isMethodHandleInvoke())
534 throw new LinkageError(m.toString());
536 assert(isResolved() && this.clazz != null);
537 this.name = m.getName();
538 if (this.type == null)
539 this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
542 throw new AbstractMethodError(this.toString());
543 if (getReferenceKind() == REF_invokeVirtual)
544 changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
545 else if (getReferenceKind() == REF_invokeInterface)
546 // invokeSpecial on a default method
547 changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
550 public MemberName asSpecial() {
551 switch (getReferenceKind()) {
552 case REF_invokeSpecial: return this;
553 case REF_invokeVirtual: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
554 case REF_invokeInterface: return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
555 case REF_newInvokeSpecial: return clone().changeReferenceKind(REF_invokeSpecial, REF_newInvokeSpecial);
557 throw new IllegalArgumentException(this.toString());
559 /** If this MN is not REF_newInvokeSpecial, return a clone with that ref. kind.
560 * In that case it must already be REF_invokeSpecial.
562 public MemberName asConstructor() {
563 switch (getReferenceKind()) {
564 case REF_invokeSpecial: return clone().changeReferenceKind(REF_newInvokeSpecial, REF_invokeSpecial);
565 case REF_newInvokeSpecial: return this;
567 throw new IllegalArgumentException(this.toString());
569 /** If this MN is a REF_invokeSpecial, return a clone with the "normal" kind
570 * REF_invokeVirtual; also switch either to REF_invokeInterface if clazz.isInterface.
571 * The end result is to get a fully virtualized version of the MN.
572 * (Note that resolving in the JVM will sometimes devirtualize, changing
573 * REF_invokeVirtual of a final to REF_invokeSpecial, and REF_invokeInterface
574 * in some corner cases to either of the previous two; this transform
575 * undoes that change under the assumption that it occurred.)
577 public MemberName asNormalOriginal() {
578 byte normalVirtual = clazz.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
579 byte refKind = getReferenceKind();
580 byte newRefKind = refKind;
581 MemberName result = this;
583 case REF_invokeInterface:
584 case REF_invokeVirtual:
585 case REF_invokeSpecial:
586 newRefKind = normalVirtual;
589 if (newRefKind == refKind)
591 result = clone().changeReferenceKind(newRefKind, refKind);
592 assert(this.referenceKindIsConsistentWith(result.getReferenceKind()));
595 /** Create a name for the given reflected constructor. The resulting name will be in a resolved state. */
596 @SuppressWarnings("LeakingThisInConstructor")
597 public MemberName(Constructor<?> ctor) {
598 ctor.getClass(); // NPE check
599 // fill in vmtarget, vmindex while we have ctor in hand:
600 MethodHandleNatives.init(this, ctor);
601 assert(isResolved() && this.clazz != null);
602 this.name = CONSTRUCTOR_NAME;
603 if (this.type == null)
604 this.type = new Object[] { void.class, ctor.getParameterTypes() };
606 /** Create a name for the given reflected field. The resulting name will be in a resolved state.
608 public MemberName(Field fld) {
611 @SuppressWarnings("LeakingThisInConstructor")
612 public MemberName(Field fld, boolean makeSetter) {
613 fld.getClass(); // NPE check
614 // fill in vmtarget, vmindex while we have fld in hand:
615 MethodHandleNatives.init(this, fld);
616 assert(isResolved() && this.clazz != null);
617 this.name = fld.getName();
618 this.type = fld.getType();
619 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
620 byte refKind = this.getReferenceKind();
621 assert(refKind == (isStatic() ? REF_getStatic : REF_getField));
623 changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind);
626 public boolean isGetter() {
627 return MethodHandleNatives.refKindIsGetter(getReferenceKind());
629 public boolean isSetter() {
630 return MethodHandleNatives.refKindIsSetter(getReferenceKind());
632 public MemberName asSetter() {
633 byte refKind = getReferenceKind();
634 assert(MethodHandleNatives.refKindIsGetter(refKind));
635 assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
636 byte setterRefKind = (byte)(refKind + (REF_putField - REF_getField));
637 return clone().changeReferenceKind(setterRefKind, refKind);
639 /** Create a name for the given class. The resulting name will be in a resolved state. */
640 public MemberName(Class<?> type) {
641 init(type.getDeclaringClass(), type.getSimpleName(), type,
642 flagsMods(IS_TYPE, type.getModifiers(), REF_NONE));
647 * Create a name for a signature-polymorphic invoker.
648 * This is a placeholder for a signature-polymorphic instance
649 * (of MH.invokeExact, etc.) that the JVM does not reify.
650 * See comments on {@link MethodHandleNatives#linkMethod}.
652 static MemberName makeMethodHandleInvoke(String name, MethodType type) {
653 return makeMethodHandleInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC);
655 static MemberName makeMethodHandleInvoke(String name, MethodType type, int mods) {
656 MemberName mem = new MemberName(MethodHandle.class, name, type, REF_invokeVirtual);
657 mem.flags |= mods; // it's not resolved, but add these modifiers anyway
658 assert(mem.isMethodHandleInvoke()) : mem;
662 // bare-bones constructor; the JVM will fill it in
665 // locally useful cloner
666 @Override protected MemberName clone() {
668 return (MemberName) super.clone();
669 } catch (CloneNotSupportedException ex) {
670 throw newInternalError(ex);
674 /** Get the definition of this member name.
675 * This may be in a super-class of the declaring class of this member.
677 public MemberName getDefinition() {
678 if (!isResolved()) throw new IllegalStateException("must be resolved: "+this);
679 if (isType()) return this;
680 MemberName res = this.clone();
684 res.resolution = res;
686 assert(res.getName().equals(this.getName()));
691 public int hashCode() {
692 return Objects.hash(clazz, getReferenceKind(), name, getType());
695 public boolean equals(Object that) {
696 return (that instanceof MemberName && this.equals((MemberName)that));
699 /** Decide if two member names have exactly the same symbolic content.
700 * Does not take into account any actual class members, so even if
701 * two member names resolve to the same actual member, they may
702 * be distinct references.
704 public boolean equals(MemberName that) {
705 if (this == that) return true;
706 if (that == null) return false;
707 return this.clazz == that.clazz
708 && this.getReferenceKind() == that.getReferenceKind()
709 && Objects.equals(this.name, that.name)
710 && Objects.equals(this.getType(), that.getType());
713 // Construction from symbolic parts, for queries:
714 /** Create a field or type name from the given components:
715 * Declaring class, name, type, reference kind.
716 * The declaring class may be supplied as null if this is to be a bare name and type.
717 * The resulting name will in an unresolved state.
719 public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) {
720 init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind));
723 /** Create a field or type name from the given components: Declaring class, name, type.
724 * The declaring class may be supplied as null if this is to be a bare name and type.
725 * The modifier flags default to zero.
726 * The resulting name will in an unresolved state.
728 public MemberName(Class<?> defClass, String name, Class<?> type, Void unused) {
729 this(defClass, name, type, REF_NONE);
732 /** Create a method or constructor name from the given components: Declaring class, name, type, modifiers.
733 * It will be a constructor if and only if the name is {@code "<init>"}.
734 * The declaring class may be supplied as null if this is to be a bare name and type.
735 * The last argument is optional, a boolean which requests REF_invokeSpecial.
736 * The resulting name will in an unresolved state.
738 public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) {
739 int initFlags = (name != null && name.equals(CONSTRUCTOR_NAME) ? IS_CONSTRUCTOR : IS_METHOD);
740 init(defClass, name, type, flagsMods(initFlags, 0, refKind));
743 /** Create a method, constructor, or field name from the given components:
744 * Reference kind, declaring class, name, type.
746 public MemberName(byte refKind, Class<?> defClass, String name, Object type) {
748 if (MethodHandleNatives.refKindIsField(refKind)) {
749 kindFlags = IS_FIELD;
750 if (!(type instanceof Class))
751 throw newIllegalArgumentException("not a field type");
752 } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
753 kindFlags = IS_METHOD;
754 if (!(type instanceof MethodType))
755 throw newIllegalArgumentException("not a method type");
756 } else if (refKind == REF_newInvokeSpecial) {
757 kindFlags = IS_CONSTRUCTOR;
758 if (!(type instanceof MethodType) ||
759 !CONSTRUCTOR_NAME.equals(name))
760 throw newIllegalArgumentException("not a constructor type or name");
762 throw newIllegalArgumentException("bad reference kind "+refKind);
764 init(defClass, name, type, flagsMods(kindFlags, 0, refKind));
767 /** Query whether this member name is resolved to a non-static, non-final method.
769 public boolean hasReceiverTypeDispatch() {
770 return MethodHandleNatives.refKindDoesDispatch(getReferenceKind());
773 /** Query whether this member name is resolved.
774 * A resolved member name is one for which the JVM has found
775 * a method, constructor, field, or type binding corresponding exactly to the name.
778 public boolean isResolved() {
779 return resolution == null;
782 private void initResolved(boolean isResolved) {
783 assert(this.resolution == null); // not initialized yet!
785 this.resolution = this;
786 assert(isResolved() == isResolved);
789 void checkForTypeAlias() {
792 if (this.type instanceof MethodType)
793 type = (MethodType) this.type;
795 this.type = type = getMethodType();
796 if (type.erase() == type) return;
797 if (VerifyAccess.isTypeVisible(type, clazz)) return;
798 throw new LinkageError("bad method type alias: "+type+" not visible from "+clazz);
801 if (this.type instanceof Class<?>)
802 type = (Class<?>) this.type;
804 this.type = type = getFieldType();
805 if (VerifyAccess.isTypeVisible(type, clazz)) return;
806 throw new LinkageError("bad field type alias: "+type+" not visible from "+clazz);
811 /** Produce a string form of this member name.
812 * For types, it is simply the type's own string (as reported by {@code toString}).
813 * For fields, it is {@code "DeclaringClass.name/type"}.
814 * For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}.
815 * If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted.
816 * If the member is unresolved, a prefix {@code "*."} is prepended.
818 @SuppressWarnings("LocalVariableHidesMemberVariable")
820 public String toString() {
822 return type.toString(); // class java.lang.String
823 // else it is a field, method, or constructor
824 StringBuilder buf = new StringBuilder();
825 if (getDeclaringClass() != null) {
826 buf.append(getName(clazz));
829 String name = getName();
830 buf.append(name == null ? "*" : name);
831 Object type = getType();
832 if (!isInvocable()) {
834 buf.append(type == null ? "*" : getName(type));
836 buf.append(type == null ? "(*)*" : getName(type));
838 byte refKind = getReferenceKind();
839 if (refKind != REF_NONE) {
841 buf.append(MethodHandleNatives.refKindName(refKind));
843 //buf.append("#").append(System.identityHashCode(this));
844 return buf.toString();
846 private static String getName(Object obj) {
847 if (obj instanceof Class<?>)
848 return ((Class<?>)obj).getName();
849 return String.valueOf(obj);
852 public IllegalAccessException makeAccessException(String message, Object from) {
853 message = message + ": "+ toString();
854 if (from != null) message += ", from " + from;
855 return new IllegalAccessException(message);
857 private String message() {
860 else if (isConstructor())
861 return "no such constructor";
863 return "no such method";
865 return "no such field";
867 public ReflectiveOperationException makeAccessException() {
868 String message = message() + ": "+ toString();
869 ReflectiveOperationException ex;
870 if (isResolved() || !(resolution instanceof NoSuchMethodError ||
871 resolution instanceof NoSuchFieldError))
872 ex = new IllegalAccessException(message);
873 else if (isConstructor())
874 ex = new NoSuchMethodException(message);
876 ex = new NoSuchMethodException(message);
878 ex = new NoSuchFieldException(message);
879 if (resolution instanceof Throwable)
880 ex.initCause((Throwable) resolution);
884 /** Actually making a query requires an access check. */
885 /*non-public*/ static Factory getFactory() {
886 return Factory.INSTANCE;
888 /** A factory type for resolving member names with the help of the VM.
889 * TBD: Define access-safe public constructors for this factory.
891 /*non-public*/ static class Factory {
892 private Factory() { } // singleton pattern
893 static Factory INSTANCE = new Factory();
895 private static int ALLOWED_FLAGS = ALL_KINDS;
898 List<MemberName> getMembers(Class<?> defc,
899 String matchName, Object matchType,
900 int matchFlags, Class<?> lookupClass) {
901 matchFlags &= ALLOWED_FLAGS;
902 String matchSig = null;
903 if (matchType != null) {
904 matchSig = BytecodeDescriptor.unparse(matchType);
905 if (matchSig.startsWith("("))
906 matchFlags &= ~(ALL_KINDS & ~IS_INVOCABLE);
908 matchFlags &= ~(ALL_KINDS & ~IS_FIELD);
910 final int BUF_MAX = 0x2000;
911 int len1 = matchName == null ? 10 : matchType == null ? 4 : 1;
912 MemberName[] buf = newMemberBuffer(len1);
914 ArrayList<MemberName[]> bufs = null;
917 bufCount = MethodHandleNatives.getMembers(defc,
918 matchName, matchSig, matchFlags,
921 if (bufCount <= buf.length) {
922 if (bufCount < 0) bufCount = 0;
923 totalCount += bufCount;
926 // JVM returned to us with an intentional overflow!
927 totalCount += buf.length;
928 int excess = bufCount - buf.length;
929 if (bufs == null) bufs = new ArrayList<>(1);
931 int len2 = buf.length;
932 len2 = Math.max(len2, excess);
933 len2 = Math.max(len2, totalCount / 4);
934 buf = newMemberBuffer(Math.min(BUF_MAX, len2));
936 ArrayList<MemberName> result = new ArrayList<>(totalCount);
938 for (MemberName[] buf0 : bufs) {
939 Collections.addAll(result, buf0);
942 result.addAll(Arrays.asList(buf).subList(0, bufCount));
943 // Signature matching is not the same as type matching, since
944 // one signature might correspond to several types.
945 // So if matchType is a Class or MethodType, refilter the results.
946 if (matchType != null && matchType != matchSig) {
947 for (Iterator<MemberName> it = result.iterator(); it.hasNext();) {
948 MemberName m = it.next();
949 if (!matchType.equals(m.getType()))
955 /** Produce a resolved version of the given member.
956 * Super types are searched (for inherited members) if {@code searchSupers} is true.
957 * Access checking is performed on behalf of the given {@code lookupClass}.
958 * If lookup fails or access is not permitted, null is returned.
959 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
961 private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass) {
962 MemberName m = ref.clone(); // JVM will side-effect the ref
963 assert(refKind == m.getReferenceKind());
965 m = MethodHandleNatives.resolve(m, lookupClass);
966 m.checkForTypeAlias();
968 } catch (LinkageError ex) {
969 // JVM reports that the "bytecode behavior" would get an error
970 assert(!m.isResolved());
974 assert(m.referenceKindIsConsistent());
975 m.initResolved(true);
976 assert(m.vminfoIsConsistent());
979 /** Produce a resolved version of the given member.
980 * Super types are searched (for inherited members) if {@code searchSupers} is true.
981 * Access checking is performed on behalf of the given {@code lookupClass}.
982 * If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown.
983 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
986 <NoSuchMemberException extends ReflectiveOperationException>
987 MemberName resolveOrFail(byte refKind, MemberName m, Class<?> lookupClass,
988 Class<NoSuchMemberException> nsmClass)
989 throws IllegalAccessException, NoSuchMemberException {
990 MemberName result = resolve(refKind, m, lookupClass);
991 if (result.isResolved())
993 ReflectiveOperationException ex = result.makeAccessException();
994 if (ex instanceof IllegalAccessException) throw (IllegalAccessException) ex;
995 throw nsmClass.cast(ex);
997 /** Produce a resolved version of the given member.
998 * Super types are searched (for inherited members) if {@code searchSupers} is true.
999 * Access checking is performed on behalf of the given {@code lookupClass}.
1000 * If lookup fails or access is not permitted, return null.
1001 * Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
1004 MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass) {
1005 MemberName result = resolve(refKind, m, lookupClass);
1006 if (result.isResolved())
1010 /** Return a list of all methods defined by the given class.
1011 * Super types are searched (for inherited members) if {@code searchSupers} is true.
1012 * Access checking is performed on behalf of the given {@code lookupClass}.
1013 * Inaccessible members are not added to the last.
1015 public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
1016 Class<?> lookupClass) {
1017 return getMethods(defc, searchSupers, null, null, lookupClass);
1019 /** Return a list of matching methods defined by the given class.
1020 * Super types are searched (for inherited members) if {@code searchSupers} is true.
1021 * Returned methods will match the name (if not null) and the type (if not null).
1022 * Access checking is performed on behalf of the given {@code lookupClass}.
1023 * Inaccessible members are not added to the last.
1025 public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
1026 String name, MethodType type, Class<?> lookupClass) {
1027 int matchFlags = IS_METHOD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1028 return getMembers(defc, name, type, matchFlags, lookupClass);
1030 /** Return a list of all constructors defined by the given class.
1031 * Access checking is performed on behalf of the given {@code lookupClass}.
1032 * Inaccessible members are not added to the last.
1034 public List<MemberName> getConstructors(Class<?> defc, Class<?> lookupClass) {
1035 return getMembers(defc, null, null, IS_CONSTRUCTOR, lookupClass);
1037 /** Return a list of all fields defined by the given class.
1038 * Super types are searched (for inherited members) if {@code searchSupers} is true.
1039 * Access checking is performed on behalf of the given {@code lookupClass}.
1040 * Inaccessible members are not added to the last.
1042 public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
1043 Class<?> lookupClass) {
1044 return getFields(defc, searchSupers, null, null, lookupClass);
1046 /** Return a list of all fields defined by the given class.
1047 * Super types are searched (for inherited members) if {@code searchSupers} is true.
1048 * Returned fields will match the name (if not null) and the type (if not null).
1049 * Access checking is performed on behalf of the given {@code lookupClass}.
1050 * Inaccessible members are not added to the last.
1052 public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
1053 String name, Class<?> type, Class<?> lookupClass) {
1054 int matchFlags = IS_FIELD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1055 return getMembers(defc, name, type, matchFlags, lookupClass);
1057 /** Return a list of all nested types defined by the given class.
1058 * Super types are searched (for inherited members) if {@code searchSupers} is true.
1059 * Access checking is performed on behalf of the given {@code lookupClass}.
1060 * Inaccessible members are not added to the last.
1062 public List<MemberName> getNestedTypes(Class<?> defc, boolean searchSupers,
1063 Class<?> lookupClass) {
1064 int matchFlags = IS_TYPE | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1065 return getMembers(defc, null, null, matchFlags, lookupClass);
1067 private static MemberName[] newMemberBuffer(int length) {
1068 MemberName[] buf = new MemberName[length];
1069 // fill the buffer with dummy structs for the JVM to fill in
1070 for (int i = 0; i < length; i++)
1071 buf[i] = new MemberName();
1077 // System.out.println("Hello world! My methods are:");
1078 // System.out.println(Factory.INSTANCE.getMethods(MemberName.class, true, null));