/* * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.lang.invoke; import sun.invoke.util.Wrapper; import java.lang.ref.WeakReference; import java.lang.ref.ReferenceQueue; import java.util.Arrays; import java.util.Collections; import java.util.List; import sun.invoke.util.BytecodeDescriptor; import static java.lang.invoke.MethodHandleStatics.*; import sun.invoke.util.VerifyType; /** * 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 more details, see the package summary. *
* 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.
* @author John Rose, JSR 292 EG
*/
public final
class MethodType implements java.io.Serializable {
private static final long serialVersionUID = 292L; // {rtype, {ptype...}}
// The rtype and ptypes fields define the structural identity of the method type:
private final Class> rtype;
private final Class>[] ptypes;
// The remaining fields are caches of various sorts:
private MethodTypeForm form; // erased form, plus cached data about primitives
private MethodType wrapAlt; // alternative wrapped/unwrapped version
private Invokers invokers; // cache of handy higher-order adapters
/**
* Check the given parameters for validity and store them into the final fields.
*/
private MethodType(Class> rtype, Class>[] ptypes) {
checkRtype(rtype);
checkPtypes(ptypes);
this.rtype = rtype;
this.ptypes = ptypes;
}
/*trusted*/ MethodTypeForm form() { return form; }
/*trusted*/ Class> rtype() { return rtype; }
/*trusted*/ Class>[] ptypes() { return ptypes; }
void setForm(MethodTypeForm f) { form = f; }
/** This number, mandated by the JVM spec as 255,
* is the maximum number of slots
* that any Java method can receive in its argument list.
* It limits both JVM signatures and method type objects.
* The longest possible invocation will look like
* {@code staticMethod(arg1, arg2, ..., arg255)} or
* {@code x.virtualMethod(arg1, arg2, ..., arg254)}.
*/
/*non-public*/ static final int MAX_JVM_ARITY = 255; // this is mandated by the JVM spec.
/** This number is the maximum arity of a method handle, 254.
* It is derived from the absolute JVM-imposed arity by subtracting one,
* which is the slot occupied by the method handle itself at the
* beginning of the argument list used to invoke the method handle.
* The longest possible invocation will look like
* {@code mh.invoke(arg1, arg2, ..., arg254)}.
*/
// Issue: Should we allow MH.invokeWithArguments to go to the full 255?
/*non-public*/ static final int MAX_MH_ARITY = MAX_JVM_ARITY-1; // deduct one for mh receiver
/** This number is the maximum arity of a method handle invoker, 253.
* It is derived from the absolute JVM-imposed arity by subtracting two,
* which are the slots occupied by invoke method handle, and the the
* target method handle, which are both at the beginning of the argument
* list used to invoke the target method handle.
* The longest possible invocation will look like
* {@code invokermh.invoke(targetmh, arg1, arg2, ..., arg253)}.
*/
/*non-public*/ static final int MAX_MH_INVOKER_ARITY = MAX_MH_ARITY-1; // deduct one more for invoker
private static void checkRtype(Class> rtype) {
rtype.equals(rtype); // null check
}
private static int checkPtype(Class> ptype) {
ptype.getClass(); //NPE
if (ptype == void.class)
throw newIllegalArgumentException("parameter type cannot be void");
if (ptype == double.class || ptype == long.class) return 1;
return 0;
}
/** Return number of extra slots (count of long/double args). */
private static int checkPtypes(Class>[] ptypes) {
int slots = 0;
for (Class> ptype : ptypes) {
slots += checkPtype(ptype);
}
checkSlotCount(ptypes.length + slots);
return slots;
}
static void checkSlotCount(int count) {
assert((MAX_JVM_ARITY & (MAX_JVM_ARITY+1)) == 0);
// MAX_JVM_ARITY must be power of 2 minus 1 for following code trick to work:
if ((count & MAX_JVM_ARITY) != count)
throw newIllegalArgumentException("bad parameter count "+count);
}
private static IndexOutOfBoundsException newIndexOutOfBoundsException(Object num) {
if (num instanceof Integer) num = "bad index: "+num;
return new IndexOutOfBoundsException(num.toString());
}
static final WeakInternSet internTable = new WeakInternSet();
static final Class>[] NO_PTYPES = {};
/**
* Finds or creates an instance of the given method type.
* @param rtype the return type
* @param ptypes the parameter types
* @return a method type with the given components
* @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
* @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
*/
public static
MethodType methodType(Class> rtype, Class>[] ptypes) {
return makeImpl(rtype, ptypes, false);
}
/**
* Finds or creates a method type with the given components.
* Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
* @return a method type with the given components
* @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
* @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
*/
public static
MethodType methodType(Class> rtype, List
* Each type is represented by its
* {@link java.lang.Class#getSimpleName simple name}.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < ptypes.length; i++) {
if (i > 0) sb.append(",");
sb.append(ptypes[i].getSimpleName());
}
sb.append(")");
sb.append(rtype.getSimpleName());
return sb.toString();
}
/*non-public*/
boolean isViewableAs(MethodType newType) {
if (!VerifyType.isNullConversion(returnType(), newType.returnType()))
return false;
int argc = parameterCount();
if (argc != newType.parameterCount())
return false;
for (int i = 0; i < argc; i++) {
if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i)))
return false;
}
return true;
}
/*non-public*/
boolean isCastableTo(MethodType newType) {
int argc = parameterCount();
if (argc != newType.parameterCount())
return false;
return true;
}
/*non-public*/
boolean isConvertibleTo(MethodType newType) {
if (!canConvert(returnType(), newType.returnType()))
return false;
int argc = parameterCount();
if (argc != newType.parameterCount())
return false;
for (int i = 0; i < argc; i++) {
if (!canConvert(newType.parameterType(i), parameterType(i)))
return false;
}
return true;
}
/*non-public*/
static boolean canConvert(Class> src, Class> dst) {
// short-circuit a few cases:
if (src == dst || dst == Object.class) return true;
// the remainder of this logic is documented in MethodHandle.asType
if (src.isPrimitive()) {
// can force void to an explicit null, a la reflect.Method.invoke
// can also force void to a primitive zero, by analogy
if (src == void.class) return true; //or !dst.isPrimitive()?
Wrapper sw = Wrapper.forPrimitiveType(src);
if (dst.isPrimitive()) {
// P->P must widen
return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
} else {
// P->R must box and widen
return dst.isAssignableFrom(sw.wrapperType());
}
} else if (dst.isPrimitive()) {
// any value can be dropped
if (dst == void.class) return true;
Wrapper dw = Wrapper.forPrimitiveType(dst);
// R->P must be able to unbox (from a dynamically chosen type) and widen
// For example:
// Byte/Number/Comparable/Object -> dw:Byte -> byte.
// Character/Comparable/Object -> dw:Character -> char
// Boolean/Comparable/Object -> dw:Boolean -> boolean
// This means that dw must be cast-compatible with src.
if (src.isAssignableFrom(dw.wrapperType())) {
return true;
}
// The above does not work if the source reference is strongly typed
// to a wrapper whose primitive must be widened. For example:
// Byte -> unbox:byte -> short/int/long/float/double
// Character -> unbox:char -> int/long/float/double
if (Wrapper.isWrapperType(src) &&
dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
// can unbox from src and then widen to dst
return true;
}
// We have already covered cases which arise due to runtime unboxing
// of a reference type which covers several wrapper types:
// Object -> cast:Integer -> unbox:int -> long/float/double
// Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
// An marginal case is Number -> dw:Character -> char, which would be OK if there were a
// subclass of Number which wraps a value that can convert to char.
// Since there is none, we don't need an extra check here to cover char or boolean.
return false;
} else {
// R->R always works, since null is always valid dynamically
return true;
}
}
/// Queries which have to do with the bytecode architecture
/** Reports the number of JVM stack slots required to invoke a method
* of this type. Note that (for historical reasons) the JVM requires
* a second stack slot to pass long and double arguments.
* So this method returns {@link #parameterCount() parameterCount} plus the
* number of long and double parameters (if any).
*
* This method is included for the benfit 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;
}
/** Reports the number of JVM stack slots which carry all parameters including and after
* the given position, which must be in the range of 0 to
* {@code parameterCount} inclusive. Successive parameters are
* more shallowly stacked, and parameters are indexed in the bytecodes
* according to their trailing edge. Thus, to obtain the depth
* in the outgoing call stack of parameter {@code N}, obtain
* the {@code parameterSlotDepth} of its trailing edge
* at position {@code N+1}.
*
* Parameters of type {@code long} and {@code double} occupy
* two stack slots (for historical reasons) and all others occupy one.
* Therefore, the number returned is the number of arguments
* including and after the given parameter,
* plus the number of long or double arguments
* at or after after the argument for the given parameter.
*
* This method is included for the benfit of applications that must
* generate bytecodes that process method handles and invokedynamic.
* @param num an index (zero-based, inclusive) within the parameter types
* @return the index of the (shallowest) JVM stack slot transmitting the
* given parameter
* @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()}
*/
/*non-public*/ int parameterSlotDepth(int num) {
if (num < 0 || num > ptypes.length)
parameterType(num); // force a range check
return form.parameterToArgSlot(num-1);
}
/** Reports the number of JVM stack slots required to receive a return value
* from a method of this type.
* If the {@link #returnType() return type} is void, it will be zero,
* else if the return type is long or double, it will be two, else one.
*
* This method is included for the benfit of applications that must
* generate bytecodes that process method handles and invokedynamic.
* @return the number of JVM stack slots (0, 1, or 2) for this type's return value
* Will be removed for PFD.
*/
/*non-public*/ int returnSlotCount() {
return form.returnSlotCount();
}
/**
* 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 calling {@link ClassLoader#loadClass(java.lang.String)}
* on 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 benfit 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
*/
public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
throws IllegalArgumentException, TypeNotPresentException
{
if (!descriptor.startsWith("(") || // also generates NPE if needed
descriptor.indexOf(')') < 0 ||
descriptor.indexOf('.') >= 0)
throw new IllegalArgumentException("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 benfit 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 bytecode type descriptor representation
*/
public String toMethodDescriptorString() {
return BytecodeDescriptor.unparse(this);
}
/*non-public*/ static String toFieldDescriptorString(Class> cls) {
return BytecodeDescriptor.unparse(cls);
}
/// Serialization.
/**
* There are no serializable fields for {@code MethodType}.
*/
private static final java.io.ObjectStreamField[] serialPersistentFields = { };
/**
* Save the {@code MethodType} instance to a stream.
*
* @serialData
* For portability, the serialized format does not refer to named fields.
* Instead, the return type and parameter type arrays are written directly
* from the {@code writeObject} method, using two calls to {@code s.writeObject}
* as follows:
*
* 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 the stream to write the object to
*/
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 the stream to read the object from
* @see #MethodType()
* @see #readResolve
* @see #writeObject
*/
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject(); // requires serialPersistentFields to be an empty array
Class> returnType = (Class>) s.readObject();
Class>[] parameterArray = (Class>[]) s.readObject();
// Probably this object will never escape, but let's check
// the field values now, just to be sure.
checkRtype(returnType);
checkPtypes(parameterArray);
parameterArray = parameterArray.clone(); // make sure it is unshared
MethodType_init(returnType, parameterArray);
}
/**
* For serialization only.
* Sets the final fields to null, pending {@code Unsafe.putObject}.
*/
private MethodType() {
this.rtype = null;
this.ptypes = null;
}
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.putObject(this, rtypeOffset, rtype);
UNSAFE.putObject(this, ptypesOffset, ptypes);
}
// Support for resetting final fields while deserializing
private static final long rtypeOffset, ptypesOffset;
static {
try {
rtypeOffset = UNSAFE.objectFieldOffset
(MethodType.class.getDeclaredField("rtype"));
ptypesOffset = UNSAFE.objectFieldOffset
(MethodType.class.getDeclaredField("ptypes"));
} catch (Exception ex) {
throw new Error(ex);
}
}
/**
* Resolves and initializes a {@code MethodType} object
* after serialization.
* @return the fully initialized {@code MethodType} object
*/
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:
return methodType(rtype, ptypes);
}
/**
* Weak intern set based on implementation of the HashSet and
* WeakHashMap, with weak values. Note: null
* values will yield NullPointerException
* Refer to implementation of WeakInternSet for details.
*
* @see java.util.HashMap
* @see java.util.HashSet
* @see java.util.WeakHashMap
* @see java.lang.ref.WeakReference
*/
private static class WeakInternSet {
// The default initial capacity -- MUST be a power of two.
private static final int DEFAULT_INITIAL_CAPACITY = 16;
// The maximum capacity, used if a higher value is implicitly specified
// by either of the constructors with arguments.
// MUST be a power of two <= 1<<30.
private static final int MAXIMUM_CAPACITY = 1 << 30;
// The load factor used when none specified in constructor.
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
// The table, resized as necessary. Length MUST Always be a power of two.
private Entry[] table;
// The number of entries contained in this set.
private int size;
// The next size value at which to resize (capacity * load factor).
private int threshold;
// The load factor for the hash table.
private final float loadFactor;
// Reference queue for cleared WeakEntries
private final ReferenceQueue
*
s.writeObject(this.returnType());
s.writeObject(this.parameterArray());
*