/* * Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.lang.invoke; import java.lang.constant.ClassDesc; import java.lang.constant.Constable; import java.lang.constant.MethodTypeDesc; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.StringJoiner; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Stream; import jdk.internal.vm.annotation.Stable; import sun.invoke.util.BytecodeDescriptor; import sun.invoke.util.VerifyType; import sun.invoke.util.Wrapper; import sun.security.util.SecurityConstants; import static java.lang.invoke.MethodHandleStatics.UNSAFE; import static java.lang.invoke.MethodHandleStatics.newIllegalArgumentException; import static java.lang.invoke.MethodType.fromDescriptor; /** * A method type represents the arguments and return type accepted and * returned by a method handle, or the arguments and return type passed * and expected by a method handle caller. Method types must be properly * matched between a method handle and all its callers, * and the JVM's operations enforce this matching at, specifically * during calls to {@link MethodHandle#invokeExact MethodHandle.invokeExact} * and {@link MethodHandle#invoke MethodHandle.invoke}, and during execution * of {@code invokedynamic} instructions. *
* The structure is a return type accompanied by any number of parameter types. * The types (primitive, {@code void}, and reference) are represented by {@link Class} objects. * (For ease of exposition, we treat {@code void} as if it were a type. * In fact, it denotes the absence of a return type.) *
* All instances of {@code MethodType} are immutable. * Two instances are completely interchangeable if they compare equal. * Equality depends on pairwise correspondence of the return and parameter types and on nothing else. *
* This type can be created only by factory methods. * All factory methods may cache values, though caching is not guaranteed. * Some factory methods are static, while others are virtual methods which * modify precursor method types, e.g., by changing a selected parameter. *
* Factory methods which operate on groups of parameter types * are systematically presented in two versions, so that both Java arrays and * Java lists can be used to work with groups of parameter types. * The query methods {@code parameterArray} and {@code parameterList} * also provide a choice between arrays and lists. *
* {@code MethodType} objects are sometimes derived from bytecode instructions * such as {@code invokedynamic}, specifically from the type descriptor strings associated * with the instructions in a class file's constant pool. *
* Like classes and strings, method types can also be represented directly * in a class file's constant pool as constants. * A method type may be loaded by an {@code ldc} instruction which refers * to a suitable {@code CONSTANT_MethodType} constant pool entry. * The entry refers to a {@code CONSTANT_Utf8} spelling for the descriptor string. * (For full details on method type constants, see sections {@jvms * 4.4.8} and {@jvms 5.4.3.5} of the Java Virtual Machine * Specification.) *
* When the JVM materializes a {@code MethodType} from a descriptor string, * all classes named in the descriptor must be accessible, and will be loaded. * (But the classes need not be initialized, as is the case with a {@code CONSTANT_Class}.) * This loading may occur at any time before the {@code MethodType} object is first derived. *
* A {@code MethodType} can be described in {@linkplain MethodTypeDesc nominal form} * if and only if all of the parameter types and return type can be described * with a {@link Class#describeConstable() nominal descriptor} represented by * {@link ClassDesc}. If a method type can be described norminally, then: *
* If any of the parameter types or return type cannot be described * nominally, i.e. {@link Class#describeConstable() Class::describeConstable} * returns an empty optional for that type, * then the method type cannot be described in nominal form: *
* The sentinel value is chosen so that reflective queries can be * made directly against the result value. * The sentinel value cannot be confused with a real parameter, * since {@code void} is never acceptable as a parameter type. * For variable arity invocation modes, the expression * {@link Class#getComponentType lastParameterType().getComponentType()} * is useful to query the type of the "varargs" parameter. * @return the last parameter type if any, else {@code void.class} * @since 10 */ public Class> lastParameterType() { int len = ptypes.length; return len == 0 ? void.class : ptypes[len-1]; } /** * Presents the parameter types as an array (a convenience method). * Changes to the array will not result in changes to the type. * @return the parameter types (as a fresh copy if necessary) */ public Class>[] parameterArray() { return ptypes.clone(); } /** * Compares the specified object with this type for equality. * That is, it returns {@code true} if and only if the specified object * is also a method type with exactly the same parameters and return type. * @param x object to compare * @see Object#equals(Object) */ // This implementation may also return true if x is a WeakEntry containing // a method type that is equal to this. This is an internal implementation // detail to allow for faster method type lookups. // See ConcurrentWeakInternSet.WeakEntry#equals(Object) @Override public boolean equals(Object x) { if (this == x) { return true; } if (x instanceof MethodType) { return equals((MethodType)x); } if (x instanceof ConcurrentWeakInternSet.WeakEntry) { Object o = ((ConcurrentWeakInternSet.WeakEntry)x).get(); if (o instanceof MethodType) { return equals((MethodType)o); } } return false; } private boolean equals(MethodType that) { return this.rtype == that.rtype && Arrays.equals(this.ptypes, that.ptypes); } /** * Returns the hash code value for this method type. * It is defined to be the same as the hashcode of a List * whose elements are the return type followed by the * parameter types. * @return the hash code value for this method type * @see Object#hashCode() * @see #equals(Object) * @see List#hashCode() */ @Override public int hashCode() { int hashCode = 31 + rtype.hashCode(); for (Class> ptype : ptypes) hashCode = 31 * hashCode + ptype.hashCode(); return hashCode; } /** * Returns a string representation of the method type, * of the form {@code "(PT0,PT1...)RT"}. * The string representation of a method type is a * parenthesis enclosed, comma separated list of type names, * followed immediately by the return type. *
* Each type is represented by its
* {@link java.lang.Class#getSimpleName simple name}.
*/
@Override
public String toString() {
StringJoiner sj = new StringJoiner(",", "(",
")" + rtype.getSimpleName());
for (int i = 0; i < ptypes.length; i++) {
sj.add(ptypes[i].getSimpleName());
}
return sj.toString();
}
/** True if my parameter list is effectively identical to the given full list,
* after skipping the given number of my own initial parameters.
* In other words, after disregarding {@code skipPos} parameters,
* my remaining parameter list is no longer than the {@code fullList}, and
* is equal to the same-length initial sublist of {@code fullList}.
*/
/*non-public*/
boolean effectivelyIdenticalParameters(int skipPos, List
* This method is included for the benefit of applications that must
* generate bytecodes that process method handles and invokedynamic.
* @return the number of JVM stack slots for this type's parameters
*/
/*non-public*/
int parameterSlotCount() {
return form.parameterSlotCount();
}
/*non-public*/
Invokers invokers() {
Invokers inv = invokers;
if (inv != null) return inv;
invokers = inv = new Invokers(this);
return inv;
}
/**
* Finds or creates an instance of a method type, given the spelling of its bytecode descriptor.
* Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
* Any class or interface name embedded in the descriptor string will be
* resolved by the given loader (or if it is null, on the system class loader).
*
* Note that it is possible to encounter method types which cannot be
* constructed by this method, because their component types are
* not all reachable from a common class loader.
*
* This method is included for the benefit of applications that must
* generate bytecodes that process method handles and {@code invokedynamic}.
* @param descriptor a bytecode-level type descriptor string "(T...)T"
* @param loader the class loader in which to look up the types
* @return a method type matching the bytecode-level type descriptor
* @throws NullPointerException if the string is null
* @throws IllegalArgumentException if the string is not well-formed
* @throws TypeNotPresentException if a named type cannot be found
* @throws SecurityException if the security manager is present and
* {@code loader} is {@code null} and the caller does not have the
* {@link RuntimePermission}{@code ("getClassLoader")}
*/
public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
throws IllegalArgumentException, TypeNotPresentException
{
if (loader == null) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
return fromDescriptor(descriptor,
(loader == null) ? ClassLoader.getSystemClassLoader() : loader);
}
/**
* Same as {@link #fromMethodDescriptorString(String, ClassLoader)}, but
* {@code null} ClassLoader means the bootstrap loader is used here.
*
* IMPORTANT: This method is preferable for JDK internal use as it more
* correctly interprets {@code null} ClassLoader than
* {@link #fromMethodDescriptorString(String, ClassLoader)}.
* Use of this method also avoids early initialization issues when system
* ClassLoader is not initialized yet.
*/
static MethodType fromDescriptor(String descriptor, ClassLoader loader)
throws IllegalArgumentException, TypeNotPresentException
{
if (!descriptor.startsWith("(") || // also generates NPE if needed
descriptor.indexOf(')') < 0 ||
descriptor.indexOf('.') >= 0)
throw newIllegalArgumentException("not a method descriptor: "+descriptor);
List
* Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}.
* Two distinct classes which share a common name but have different class loaders
* will appear identical when viewed within descriptor strings.
*
* This method is included for the benefit of applications that must
* generate bytecodes that process method handles and {@code invokedynamic}.
* {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString},
* because the latter requires a suitable class loader argument.
* @return the descriptor string for this method type
* @jvms 4.3.3 Method Descriptors
* @see Nominal Descriptor for {@code MethodType}
*/
public String toMethodDescriptorString() {
String desc = methodDescriptor;
if (desc == null) {
desc = BytecodeDescriptor.unparseMethod(this.rtype, this.ptypes);
methodDescriptor = desc;
}
return desc;
}
/**
* Returns a descriptor string for this method type.
*
*
* If this method type can be described nominally,
* then the result is a method type descriptor string (JVMS {@jvms 4.3.3}).
* {@link MethodTypeDesc MethodTypeDesc} for this method type
* can be produced by calling {@link MethodTypeDesc#ofDescriptor(String)
* MethodTypeDesc::ofDescriptor} with the result descriptor string.
*
* If this method type cannot be described nominally
* and the result is a string of the form:
*
* The deserialized field values are checked as if they were
* provided to the factory method {@link #methodType(Class,Class[]) methodType}.
* For example, null values, or {@code void} parameter types,
* will lead to exceptions during deserialization.
* @param s the stream to write the object to
* @throws java.io.IOException if there is a problem writing the object
*/
@java.io.Serial
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
s.defaultWriteObject(); // requires serialPersistentFields to be an empty array
s.writeObject(returnType());
s.writeObject(parameterArray());
}
/**
* Reconstitute the {@code MethodType} instance from a stream (that is,
* deserialize it).
* This instance is a scratch object with bogus final fields.
* It provides the parameters to the factory method called by
* {@link #readResolve readResolve}.
* After that call it is discarded.
* @param s the stream to read the object from
* @throws java.io.IOException if there is a problem reading the object
* @throws ClassNotFoundException if one of the component classes cannot be resolved
* @see #readResolve
* @see #writeObject
*/
@java.io.Serial
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
// Assign temporary defaults in case this object escapes
MethodType_init(void.class, NO_PTYPES);
s.defaultReadObject(); // requires serialPersistentFields to be an empty array
Class> returnType = (Class>) s.readObject();
Class>[] parameterArray = (Class>[]) s.readObject();
parameterArray = parameterArray.clone(); // make sure it is unshared
// Assign deserialized values
MethodType_init(returnType, parameterArray);
}
// Initialization of state for deserialization only
private void MethodType_init(Class> rtype, Class>[] ptypes) {
// In order to communicate these values to readResolve, we must
// store them into the implementation-specific final fields.
checkRtype(rtype);
checkPtypes(ptypes);
UNSAFE.putReference(this, OffsetHolder.rtypeOffset, rtype);
UNSAFE.putReference(this, OffsetHolder.ptypesOffset, ptypes);
}
// Support for resetting final fields while deserializing. Implement Holder
// pattern to make the rarely needed offset calculation lazy.
private static class OffsetHolder {
static final long rtypeOffset
= UNSAFE.objectFieldOffset(MethodType.class, "rtype");
static final long ptypesOffset
= UNSAFE.objectFieldOffset(MethodType.class, "ptypes");
}
/**
* Resolves and initializes a {@code MethodType} object
* after serialization.
* @return the fully initialized {@code MethodType} object
*/
@java.io.Serial
private Object readResolve() {
// Do not use a trusted path for deserialization:
// return makeImpl(rtype, ptypes, true);
// Verify all operands, and make sure ptypes is unshared:
try {
return methodType(rtype, ptypes);
} finally {
// Re-assign defaults in case this object escapes
MethodType_init(void.class, NO_PTYPES);
}
}
/**
* Simple implementation of weak concurrent intern set.
*
* @param {@code "(
* where {@code
* {@code
s.writeObject(this.returnType());
s.writeObject(this.parameterArray());
* }