Home » openjdk-7 » java.lang.invoke » [javadoc | source]

    1   /*
    2    * Copyright (c) 2008, 2011, 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.Wrapper;
   29   import java.util.Arrays;
   30   import java.util.Collections;
   31   import java.util.HashMap;
   32   import java.util.List;
   33   import sun.invoke.util.BytecodeDescriptor;
   34   import static java.lang.invoke.MethodHandleStatics.*;
   35   
   36   /**
   37    * A method type represents the arguments and return type accepted and
   38    * returned by a method handle, or the arguments and return type passed
   39    * and expected  by a method handle caller.  Method types must be properly
   40    * matched between a method handle and all its callers,
   41    * and the JVM's operations enforce this matching at, specifically
   42    * during calls to {@link MethodHandle#invokeExact MethodHandle.invokeExact}
   43    * and {@link MethodHandle#invoke MethodHandle.invoke}, and during execution
   44    * of {@code invokedynamic} instructions.
   45    * <p>
   46    * The structure is a return type accompanied by any number of parameter types.
   47    * The types (primitive, {@code void}, and reference) are represented by {@link Class} objects.
   48    * (For ease of exposition, we treat {@code void} as if it were a type.
   49    * In fact, it denotes the absence of a return type.)
   50    * <p>
   51    * All instances of {@code MethodType} are immutable.
   52    * Two instances are completely interchangeable if they compare equal.
   53    * Equality depends on pairwise correspondence of the return and parameter types and on nothing else.
   54    * <p>
   55    * This type can be created only by factory methods.
   56    * All factory methods may cache values, though caching is not guaranteed.
   57    * Some factory methods are static, while others are virtual methods which
   58    * modify precursor method types, e.g., by changing a selected parameter.
   59    * <p>
   60    * Factory methods which operate on groups of parameter types
   61    * are systematically presented in two versions, so that both Java arrays and
   62    * Java lists can be used to work with groups of parameter types.
   63    * The query methods {@code parameterArray} and {@code parameterList}
   64    * also provide a choice between arrays and lists.
   65    * <p>
   66    * {@code MethodType} objects are sometimes derived from bytecode instructions
   67    * such as {@code invokedynamic}, specifically from the type descriptor strings associated
   68    * with the instructions in a class file's constant pool.
   69    * <p>
   70    * Like classes and strings, method types can also be represented directly
   71    * in a class file's constant pool as constants.
   72    * A method type may be loaded by an {@code ldc} instruction which refers
   73    * to a suitable {@code CONSTANT_MethodType} constant pool entry.
   74    * The entry refers to a {@code CONSTANT_Utf8} spelling for the descriptor string.
   75    * For more details, see the <a href="package-summary.html#mtcon">package summary</a>.
   76    * <p>
   77    * When the JVM materializes a {@code MethodType} from a descriptor string,
   78    * all classes named in the descriptor must be accessible, and will be loaded.
   79    * (But the classes need not be initialized, as is the case with a {@code CONSTANT_Class}.)
   80    * This loading may occur at any time before the {@code MethodType} object is first derived.
   81    * @author John Rose, JSR 292 EG
   82    */
   83   public final
   84   class MethodType implements java.io.Serializable {
   85       private static final long serialVersionUID = 292L;  // {rtype, {ptype...}}
   86   
   87       // The rtype and ptypes fields define the structural identity of the method type:
   88       private final Class<?>   rtype;
   89       private final Class<?>[] ptypes;
   90   
   91       // The remaining fields are caches of various sorts:
   92       private MethodTypeForm form; // erased form, plus cached data about primitives
   93       private MethodType wrapAlt;  // alternative wrapped/unwrapped version
   94       private Invokers invokers;   // cache of handy higher-order adapters
   95   
   96       /**
   97        * Check the given parameters for validity and store them into the final fields.
   98        */
   99       private MethodType(Class<?> rtype, Class<?>[] ptypes) {
  100           checkRtype(rtype);
  101           checkPtypes(ptypes);
  102           this.rtype = rtype;
  103           this.ptypes = ptypes;
  104       }
  105   
  106       /*trusted*/ MethodTypeForm form() { return form; }
  107       /*trusted*/ Class<?> rtype() { return rtype; }
  108       /*trusted*/ Class<?>[] ptypes() { return ptypes; }
  109   
  110       private static void checkRtype(Class<?> rtype) {
  111           rtype.equals(rtype);  // null check
  112       }
  113       private static int checkPtype(Class<?> ptype) {
  114           ptype.getClass();  //NPE
  115           if (ptype == void.class)
  116               throw newIllegalArgumentException("parameter type cannot be void");
  117           if (ptype == double.class || ptype == long.class)  return 1;
  118           return 0;
  119       }
  120       /** Return number of extra slots (count of long/double args). */
  121       private static int checkPtypes(Class<?>[] ptypes) {
  122           int slots = 0;
  123           for (Class<?> ptype : ptypes) {
  124               slots += checkPtype(ptype);
  125           }
  126           checkSlotCount(ptypes.length + slots);
  127           return slots;
  128       }
  129       private static void checkSlotCount(int count) {
  130           if ((count & 0xFF) != count)
  131               throw newIllegalArgumentException("bad parameter count "+count);
  132       }
  133       private static IndexOutOfBoundsException newIndexOutOfBoundsException(Object num) {
  134           if (num instanceof Integer)  num = "bad index: "+num;
  135           return new IndexOutOfBoundsException(num.toString());
  136       }
  137   
  138       static final HashMap<MethodType,MethodType> internTable
  139               = new HashMap<MethodType, MethodType>();
  140   
  141       static final Class<?>[] NO_PTYPES = {};
  142   
  143       /**
  144        * Finds or creates an instance of the given method type.
  145        * @param rtype  the return type
  146        * @param ptypes the parameter types
  147        * @return a method type with the given components
  148        * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
  149        * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
  150        */
  151       public static
  152       MethodType methodType(Class<?> rtype, Class<?>[] ptypes) {
  153           return makeImpl(rtype, ptypes, false);
  154       }
  155   
  156       /**
  157        * Finds or creates a method type with the given components.
  158        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  159        * @return a method type with the given components
  160        * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
  161        * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
  162        */
  163       public static
  164       MethodType methodType(Class<?> rtype, List<Class<?>> ptypes) {
  165           boolean notrust = false;  // random List impl. could return evil ptypes array
  166           return makeImpl(rtype, listToArray(ptypes), notrust);
  167       }
  168   
  169       private static Class<?>[] listToArray(List<Class<?>> ptypes) {
  170           // sanity check the size before the toArray call, since size might be huge
  171           checkSlotCount(ptypes.size());
  172           return ptypes.toArray(NO_PTYPES);
  173       }
  174   
  175       /**
  176        * Finds or creates a method type with the given components.
  177        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  178        * The leading parameter type is prepended to the remaining array.
  179        * @return a method type with the given components
  180        * @throws NullPointerException if {@code rtype} or {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is null
  181        * @throws IllegalArgumentException if {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is {@code void.class}
  182        */
  183       public static
  184       MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) {
  185           Class<?>[] ptypes1 = new Class<?>[1+ptypes.length];
  186           ptypes1[0] = ptype0;
  187           System.arraycopy(ptypes, 0, ptypes1, 1, ptypes.length);
  188           return makeImpl(rtype, ptypes1, true);
  189       }
  190   
  191       /**
  192        * Finds or creates a method type with the given components.
  193        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  194        * The resulting method has no parameter types.
  195        * @return a method type with the given return value
  196        * @throws NullPointerException if {@code rtype} is null
  197        */
  198       public static
  199       MethodType methodType(Class<?> rtype) {
  200           return makeImpl(rtype, NO_PTYPES, true);
  201       }
  202   
  203       /**
  204        * Finds or creates a method type with the given components.
  205        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  206        * The resulting method has the single given parameter type.
  207        * @return a method type with the given return value and parameter type
  208        * @throws NullPointerException if {@code rtype} or {@code ptype0} is null
  209        * @throws IllegalArgumentException if {@code ptype0} is {@code void.class}
  210        */
  211       public static
  212       MethodType methodType(Class<?> rtype, Class<?> ptype0) {
  213           return makeImpl(rtype, new Class<?>[]{ ptype0 }, true);
  214       }
  215   
  216       /**
  217        * Finds or creates a method type with the given components.
  218        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  219        * The resulting method has the same parameter types as {@code ptypes},
  220        * and the specified return type.
  221        * @throws NullPointerException if {@code rtype} or {@code ptypes} is null
  222        */
  223       public static
  224       MethodType methodType(Class<?> rtype, MethodType ptypes) {
  225           return makeImpl(rtype, ptypes.ptypes, true);
  226       }
  227   
  228       /**
  229        * Sole factory method to find or create an interned method type.
  230        * @param rtype desired return type
  231        * @param ptypes desired parameter types
  232        * @param trusted whether the ptypes can be used without cloning
  233        * @return the unique method type of the desired structure
  234        */
  235       /*trusted*/ static
  236       MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
  237           if (ptypes.length == 0) {
  238               ptypes = NO_PTYPES; trusted = true;
  239           }
  240           MethodType mt1 = new MethodType(rtype, ptypes);
  241           MethodType mt0;
  242           synchronized (internTable) {
  243               mt0 = internTable.get(mt1);
  244               if (mt0 != null)
  245                   return mt0;
  246           }
  247           if (!trusted)
  248               // defensively copy the array passed in by the user
  249               mt1 = new MethodType(rtype, ptypes.clone());
  250           // promote the object to the Real Thing, and reprobe
  251           MethodTypeForm form = MethodTypeForm.findForm(mt1);
  252           mt1.form = form;
  253           if (form.erasedType == mt1) {
  254               // This is a principal (erased) type; show it to the JVM.
  255               MethodHandleNatives.init(mt1);
  256           }
  257           synchronized (internTable) {
  258               mt0 = internTable.get(mt1);
  259               if (mt0 != null)
  260                   return mt0;
  261               internTable.put(mt1, mt1);
  262           }
  263           return mt1;
  264       }
  265   
  266       private static final MethodType[] objectOnlyTypes = new MethodType[20];
  267   
  268       /**
  269        * Finds or creates a method type whose components are {@code Object} with an optional trailing {@code Object[]} array.
  270        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  271        * All parameters and the return type will be {@code Object},
  272        * except the final array parameter if any, which will be {@code Object[]}.
  273        * @param objectArgCount number of parameters (excluding the final array parameter if any)
  274        * @param finalArray whether there will be a trailing array parameter, of type {@code Object[]}
  275        * @return a generally applicable method type, for all calls of the given fixed argument count and a collected array of further arguments
  276        * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255 (or 254, if {@code finalArray} is true)
  277        * @see #genericMethodType(int)
  278        */
  279       public static
  280       MethodType genericMethodType(int objectArgCount, boolean finalArray) {
  281           MethodType mt;
  282           checkSlotCount(objectArgCount);
  283           int ivarargs = (!finalArray ? 0 : 1);
  284           int ootIndex = objectArgCount*2 + ivarargs;
  285           if (ootIndex < objectOnlyTypes.length) {
  286               mt = objectOnlyTypes[ootIndex];
  287               if (mt != null)  return mt;
  288           }
  289           Class<?>[] ptypes = new Class<?>[objectArgCount + ivarargs];
  290           Arrays.fill(ptypes, Object.class);
  291           if (ivarargs != 0)  ptypes[objectArgCount] = Object[].class;
  292           mt = makeImpl(Object.class, ptypes, true);
  293           if (ootIndex < objectOnlyTypes.length) {
  294               objectOnlyTypes[ootIndex] = mt;     // cache it here also!
  295           }
  296           return mt;
  297       }
  298   
  299       /**
  300        * Finds or creates a method type whose components are all {@code Object}.
  301        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  302        * All parameters and the return type will be Object.
  303        * @param objectArgCount number of parameters
  304        * @return a generally applicable method type, for all calls of the given argument count
  305        * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255
  306        * @see #genericMethodType(int, boolean)
  307        */
  308       public static
  309       MethodType genericMethodType(int objectArgCount) {
  310           return genericMethodType(objectArgCount, false);
  311       }
  312   
  313       /**
  314        * Finds or creates a method type with a single different parameter type.
  315        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  316        * @param num    the index (zero-based) of the parameter type to change
  317        * @param nptype a new parameter type to replace the old one with
  318        * @return the same type, except with the selected parameter changed
  319        * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
  320        * @throws IllegalArgumentException if {@code nptype} is {@code void.class}
  321        * @throws NullPointerException if {@code nptype} is null
  322        */
  323       public MethodType changeParameterType(int num, Class<?> nptype) {
  324           if (parameterType(num) == nptype)  return this;
  325           checkPtype(nptype);
  326           Class<?>[] nptypes = ptypes.clone();
  327           nptypes[num] = nptype;
  328           return makeImpl(rtype, nptypes, true);
  329       }
  330   
  331       /**
  332        * Finds or creates a method type with additional parameter types.
  333        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  334        * @param num    the position (zero-based) of the inserted parameter type(s)
  335        * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
  336        * @return the same type, except with the selected parameter(s) inserted
  337        * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
  338        * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
  339        *                                  or if the resulting method type would have more than 255 parameter slots
  340        * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
  341        */
  342       public MethodType insertParameterTypes(int num, Class<?>... ptypesToInsert) {
  343           int len = ptypes.length;
  344           if (num < 0 || num > len)
  345               throw newIndexOutOfBoundsException(num);
  346           int ins = checkPtypes(ptypesToInsert);
  347           checkSlotCount(parameterSlotCount() + ptypesToInsert.length + ins);
  348           int ilen = ptypesToInsert.length;
  349           if (ilen == 0)  return this;
  350           Class<?>[] nptypes = Arrays.copyOfRange(ptypes, 0, len+ilen);
  351           System.arraycopy(nptypes, num, nptypes, num+ilen, len-num);
  352           System.arraycopy(ptypesToInsert, 0, nptypes, num, ilen);
  353           return makeImpl(rtype, nptypes, true);
  354       }
  355   
  356       /**
  357        * Finds or creates a method type with additional parameter types.
  358        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  359        * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
  360        * @return the same type, except with the selected parameter(s) appended
  361        * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
  362        *                                  or if the resulting method type would have more than 255 parameter slots
  363        * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
  364        */
  365       public MethodType appendParameterTypes(Class<?>... ptypesToInsert) {
  366           return insertParameterTypes(parameterCount(), ptypesToInsert);
  367       }
  368   
  369       /**
  370        * Finds or creates a method type with additional parameter types.
  371        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  372        * @param num    the position (zero-based) of the inserted parameter type(s)
  373        * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
  374        * @return the same type, except with the selected parameter(s) inserted
  375        * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
  376        * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
  377        *                                  or if the resulting method type would have more than 255 parameter slots
  378        * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
  379        */
  380       public MethodType insertParameterTypes(int num, List<Class<?>> ptypesToInsert) {
  381           return insertParameterTypes(num, listToArray(ptypesToInsert));
  382       }
  383   
  384       /**
  385        * Finds or creates a method type with additional parameter types.
  386        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  387        * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
  388        * @return the same type, except with the selected parameter(s) appended
  389        * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
  390        *                                  or if the resulting method type would have more than 255 parameter slots
  391        * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
  392        */
  393       public MethodType appendParameterTypes(List<Class<?>> ptypesToInsert) {
  394           return insertParameterTypes(parameterCount(), ptypesToInsert);
  395       }
  396   
  397       /**
  398        * Finds or creates a method type with some parameter types omitted.
  399        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  400        * @param start  the index (zero-based) of the first parameter type to remove
  401        * @param end    the index (greater than {@code start}) of the first parameter type after not to remove
  402        * @return the same type, except with the selected parameter(s) removed
  403        * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
  404        *                                  or if {@code end} is negative or greater than {@code parameterCount()}
  405        *                                  or if {@code start} is greater than {@code end}
  406        */
  407       public MethodType dropParameterTypes(int start, int end) {
  408           int len = ptypes.length;
  409           if (!(0 <= start && start <= end && end <= len))
  410               throw newIndexOutOfBoundsException("start="+start+" end="+end);
  411           if (start == end)  return this;
  412           Class<?>[] nptypes;
  413           if (start == 0) {
  414               if (end == len) {
  415                   // drop all parameters
  416                   nptypes = NO_PTYPES;
  417               } else {
  418                   // drop initial parameter(s)
  419                   nptypes = Arrays.copyOfRange(ptypes, end, len);
  420               }
  421           } else {
  422               if (end == len) {
  423                   // drop trailing parameter(s)
  424                   nptypes = Arrays.copyOfRange(ptypes, 0, start);
  425               } else {
  426                   int tail = len - end;
  427                   nptypes = Arrays.copyOfRange(ptypes, 0, start + tail);
  428                   System.arraycopy(ptypes, end, nptypes, start, tail);
  429               }
  430           }
  431           return makeImpl(rtype, nptypes, true);
  432       }
  433   
  434       /**
  435        * Finds or creates a method type with a different return type.
  436        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  437        * @param nrtype a return parameter type to replace the old one with
  438        * @return the same type, except with the return type change
  439        * @throws NullPointerException if {@code nrtype} is null
  440        */
  441       public MethodType changeReturnType(Class<?> nrtype) {
  442           if (returnType() == nrtype)  return this;
  443           return makeImpl(nrtype, ptypes, true);
  444       }
  445   
  446       /**
  447        * Reports if this type contains a primitive argument or return value.
  448        * The return type {@code void} counts as a primitive.
  449        * @return true if any of the types are primitives
  450        */
  451       public boolean hasPrimitives() {
  452           return form.hasPrimitives();
  453       }
  454   
  455       /**
  456        * Reports if this type contains a wrapper argument or return value.
  457        * Wrappers are types which box primitive values, such as {@link Integer}.
  458        * The reference type {@code java.lang.Void} counts as a wrapper,
  459        * if it occurs as a return type.
  460        * @return true if any of the types are wrappers
  461        */
  462       public boolean hasWrappers() {
  463           return unwrap() != this;
  464       }
  465   
  466       /**
  467        * Erases all reference types to {@code Object}.
  468        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  469        * All primitive types (including {@code void}) will remain unchanged.
  470        * @return a version of the original type with all reference types replaced
  471        */
  472       public MethodType erase() {
  473           return form.erasedType();
  474       }
  475   
  476       /**
  477        * Converts all types, both reference and primitive, to {@code Object}.
  478        * Convenience method for {@link #genericMethodType(int) genericMethodType}.
  479        * The expression {@code type.wrap().erase()} produces the same value
  480        * as {@code type.generic()}.
  481        * @return a version of the original type with all types replaced
  482        */
  483       public MethodType generic() {
  484           return genericMethodType(parameterCount());
  485       }
  486   
  487       /**
  488        * Converts all primitive types to their corresponding wrapper types.
  489        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  490        * All reference types (including wrapper types) will remain unchanged.
  491        * A {@code void} return type is changed to the type {@code java.lang.Void}.
  492        * The expression {@code type.wrap().erase()} produces the same value
  493        * as {@code type.generic()}.
  494        * @return a version of the original type with all primitive types replaced
  495        */
  496       public MethodType wrap() {
  497           return hasPrimitives() ? wrapWithPrims(this) : this;
  498       }
  499   
  500       /**
  501        * Converts all wrapper types to their corresponding primitive types.
  502        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  503        * All primitive types (including {@code void}) will remain unchanged.
  504        * A return type of {@code java.lang.Void} is changed to {@code void}.
  505        * @return a version of the original type with all wrapper types replaced
  506        */
  507       public MethodType unwrap() {
  508           MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this);
  509           return unwrapWithNoPrims(noprims);
  510       }
  511   
  512       private static MethodType wrapWithPrims(MethodType pt) {
  513           assert(pt.hasPrimitives());
  514           MethodType wt = pt.wrapAlt;
  515           if (wt == null) {
  516               // fill in lazily
  517               wt = MethodTypeForm.canonicalize(pt, MethodTypeForm.WRAP, MethodTypeForm.WRAP);
  518               assert(wt != null);
  519               pt.wrapAlt = wt;
  520           }
  521           return wt;
  522       }
  523   
  524       private static MethodType unwrapWithNoPrims(MethodType wt) {
  525           assert(!wt.hasPrimitives());
  526           MethodType uwt = wt.wrapAlt;
  527           if (uwt == null) {
  528               // fill in lazily
  529               uwt = MethodTypeForm.canonicalize(wt, MethodTypeForm.UNWRAP, MethodTypeForm.UNWRAP);
  530               if (uwt == null)
  531                   uwt = wt;    // type has no wrappers or prims at all
  532               wt.wrapAlt = uwt;
  533           }
  534           return uwt;
  535       }
  536   
  537       /**
  538        * Returns the parameter type at the specified index, within this method type.
  539        * @param num the index (zero-based) of the desired parameter type
  540        * @return the selected parameter type
  541        * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
  542        */
  543       public Class<?> parameterType(int num) {
  544           return ptypes[num];
  545       }
  546       /**
  547        * Returns the number of parameter types in this method type.
  548        * @return the number of parameter types
  549        */
  550       public int parameterCount() {
  551           return ptypes.length;
  552       }
  553       /**
  554        * Returns the return type of this method type.
  555        * @return the return type
  556        */
  557       public Class<?> returnType() {
  558           return rtype;
  559       }
  560   
  561       /**
  562        * Presents the parameter types as a list (a convenience method).
  563        * The list will be immutable.
  564        * @return the parameter types (as an immutable list)
  565        */
  566       public List<Class<?>> parameterList() {
  567           return Collections.unmodifiableList(Arrays.asList(ptypes));
  568       }
  569   
  570       /**
  571        * Presents the parameter types as an array (a convenience method).
  572        * Changes to the array will not result in changes to the type.
  573        * @return the parameter types (as a fresh copy if necessary)
  574        */
  575       public Class<?>[] parameterArray() {
  576           return ptypes.clone();
  577       }
  578   
  579       /**
  580        * Compares the specified object with this type for equality.
  581        * That is, it returns <tt>true</tt> if and only if the specified object
  582        * is also a method type with exactly the same parameters and return type.
  583        * @param x object to compare
  584        * @see Object#equals(Object)
  585        */
  586       @Override
  587       public boolean equals(Object x) {
  588           return this == x || x instanceof MethodType && equals((MethodType)x);
  589       }
  590   
  591       private boolean equals(MethodType that) {
  592           return this.rtype == that.rtype
  593               && Arrays.equals(this.ptypes, that.ptypes);
  594       }
  595   
  596       /**
  597        * Returns the hash code value for this method type.
  598        * It is defined to be the same as the hashcode of a List
  599        * whose elements are the return type followed by the
  600        * parameter types.
  601        * @return the hash code value for this method type
  602        * @see Object#hashCode()
  603        * @see #equals(Object)
  604        * @see List#hashCode()
  605        */
  606       @Override
  607       public int hashCode() {
  608         int hashCode = 31 + rtype.hashCode();
  609         for (Class<?> ptype : ptypes)
  610             hashCode = 31*hashCode + ptype.hashCode();
  611         return hashCode;
  612       }
  613   
  614       /**
  615        * Returns a string representation of the method type,
  616        * of the form {@code "(PT0,PT1...)RT"}.
  617        * The string representation of a method type is a
  618        * parenthesis enclosed, comma separated list of type names,
  619        * followed immediately by the return type.
  620        * <p>
  621        * Each type is represented by its
  622        * {@link java.lang.Class#getSimpleName simple name}.
  623        */
  624       @Override
  625       public String toString() {
  626           StringBuilder sb = new StringBuilder();
  627           sb.append("(");
  628           for (int i = 0; i < ptypes.length; i++) {
  629               if (i > 0)  sb.append(",");
  630               sb.append(ptypes[i].getSimpleName());
  631           }
  632           sb.append(")");
  633           sb.append(rtype.getSimpleName());
  634           return sb.toString();
  635       }
  636   
  637   
  638       /*non-public*/
  639       boolean isConvertibleTo(MethodType newType) {
  640           if (!canConvert(returnType(), newType.returnType()))
  641               return false;
  642           int argc = parameterCount();
  643           if (argc != newType.parameterCount())
  644               return false;
  645           for (int i = 0; i < argc; i++) {
  646               if (!canConvert(newType.parameterType(i), parameterType(i)))
  647                   return false;
  648           }
  649           return true;
  650       }
  651       /*non-public*/
  652       static boolean canConvert(Class<?> src, Class<?> dst) {
  653           // short-circuit a few cases:
  654           if (src == dst || dst == Object.class)  return true;
  655           // the remainder of this logic is documented in MethodHandle.asType
  656           if (src.isPrimitive()) {
  657               // can force void to an explicit null, a la reflect.Method.invoke
  658               // can also force void to a primitive zero, by analogy
  659               if (src == void.class)  return true;  //or !dst.isPrimitive()?
  660               Wrapper sw = Wrapper.forPrimitiveType(src);
  661               if (dst.isPrimitive()) {
  662                   // P->P must widen
  663                   return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
  664               } else {
  665                   // P->R must box and widen
  666                   return dst.isAssignableFrom(sw.wrapperType());
  667               }
  668           } else if (dst.isPrimitive()) {
  669               // any value can be dropped
  670               if (dst == void.class)  return true;
  671               Wrapper dw = Wrapper.forPrimitiveType(dst);
  672               // R->P must be able to unbox (from a dynamically chosen type) and widen
  673               // For example:
  674               //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
  675               //   Character/Comparable/Object -> dw:Character -> char
  676               //   Boolean/Comparable/Object -> dw:Boolean -> boolean
  677               // This means that dw must be cast-compatible with src.
  678               if (src.isAssignableFrom(dw.wrapperType())) {
  679                   return true;
  680               }
  681               // The above does not work if the source reference is strongly typed
  682               // to a wrapper whose primitive must be widened.  For example:
  683               //   Byte -> unbox:byte -> short/int/long/float/double
  684               //   Character -> unbox:char -> int/long/float/double
  685               if (Wrapper.isWrapperType(src) &&
  686                   dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
  687                   // can unbox from src and then widen to dst
  688                   return true;
  689               }
  690               // We have already covered cases which arise due to runtime unboxing
  691               // of a reference type which covers several wrapper types:
  692               //   Object -> cast:Integer -> unbox:int -> long/float/double
  693               //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
  694               // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
  695               // subclass of Number which wraps a value that can convert to char.
  696               // Since there is none, we don't need an extra check here to cover char or boolean.
  697               return false;
  698           } else {
  699               // R->R always works, since null is always valid dynamically
  700               return true;
  701           }
  702       }
  703   
  704       /// Queries which have to do with the bytecode architecture
  705   
  706       /** Reports the number of JVM stack slots required to invoke a method
  707        * of this type.  Note that (for historical reasons) the JVM requires
  708        * a second stack slot to pass long and double arguments.
  709        * So this method returns {@link #parameterCount() parameterCount} plus the
  710        * number of long and double parameters (if any).
  711        * <p>
  712        * This method is included for the benfit of applications that must
  713        * generate bytecodes that process method handles and invokedynamic.
  714        * @return the number of JVM stack slots for this type's parameters
  715        */
  716       /*non-public*/ int parameterSlotCount() {
  717           return form.parameterSlotCount();
  718       }
  719   
  720       /*non-public*/ Invokers invokers() {
  721           Invokers inv = invokers;
  722           if (inv != null)  return inv;
  723           invokers = inv = new Invokers(this);
  724           return inv;
  725       }
  726   
  727       /** Reports the number of JVM stack slots which carry all parameters including and after
  728        * the given position, which must be in the range of 0 to
  729        * {@code parameterCount} inclusive.  Successive parameters are
  730        * more shallowly stacked, and parameters are indexed in the bytecodes
  731        * according to their trailing edge.  Thus, to obtain the depth
  732        * in the outgoing call stack of parameter {@code N}, obtain
  733        * the {@code parameterSlotDepth} of its trailing edge
  734        * at position {@code N+1}.
  735        * <p>
  736        * Parameters of type {@code long} and {@code double} occupy
  737        * two stack slots (for historical reasons) and all others occupy one.
  738        * Therefore, the number returned is the number of arguments
  739        * <em>including</em> and <em>after</em> the given parameter,
  740        * <em>plus</em> the number of long or double arguments
  741        * at or after after the argument for the given parameter.
  742        * <p>
  743        * This method is included for the benfit of applications that must
  744        * generate bytecodes that process method handles and invokedynamic.
  745        * @param num an index (zero-based, inclusive) within the parameter types
  746        * @return the index of the (shallowest) JVM stack slot transmitting the
  747        *         given parameter
  748        * @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()}
  749        */
  750       /*non-public*/ int parameterSlotDepth(int num) {
  751           if (num < 0 || num > ptypes.length)
  752               parameterType(num);  // force a range check
  753           return form.parameterToArgSlot(num-1);
  754       }
  755   
  756       /** Reports the number of JVM stack slots required to receive a return value
  757        * from a method of this type.
  758        * If the {@link #returnType() return type} is void, it will be zero,
  759        * else if the return type is long or double, it will be two, else one.
  760        * <p>
  761        * This method is included for the benfit of applications that must
  762        * generate bytecodes that process method handles and invokedynamic.
  763        * @return the number of JVM stack slots (0, 1, or 2) for this type's return value
  764        * Will be removed for PFD.
  765        */
  766       /*non-public*/ int returnSlotCount() {
  767           return form.returnSlotCount();
  768       }
  769   
  770       /**
  771        * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor.
  772        * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
  773        * Any class or interface name embedded in the descriptor string
  774        * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)}
  775        * on the given loader (or if it is null, on the system class loader).
  776        * <p>
  777        * Note that it is possible to encounter method types which cannot be
  778        * constructed by this method, because their component types are
  779        * not all reachable from a common class loader.
  780        * <p>
  781        * This method is included for the benfit of applications that must
  782        * generate bytecodes that process method handles and {@code invokedynamic}.
  783        * @param descriptor a bytecode-level type descriptor string "(T...)T"
  784        * @param loader the class loader in which to look up the types
  785        * @return a method type matching the bytecode-level type descriptor
  786        * @throws NullPointerException if the string is null
  787        * @throws IllegalArgumentException if the string is not well-formed
  788        * @throws TypeNotPresentException if a named type cannot be found
  789        */
  790       public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
  791           throws IllegalArgumentException, TypeNotPresentException
  792       {
  793           if (!descriptor.startsWith("(") ||  // also generates NPE if needed
  794               descriptor.indexOf(')') < 0 ||
  795               descriptor.indexOf('.') >= 0)
  796               throw new IllegalArgumentException("not a method descriptor: "+descriptor);
  797           List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader);
  798           Class<?> rtype = types.remove(types.size() - 1);
  799           checkSlotCount(types.size());
  800           Class<?>[] ptypes = listToArray(types);
  801           return makeImpl(rtype, ptypes, true);
  802       }
  803   
  804       /**
  805        * Produces a bytecode descriptor representation of the method type.
  806        * <p>
  807        * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}.
  808        * Two distinct classes which share a common name but have different class loaders
  809        * will appear identical when viewed within descriptor strings.
  810        * <p>
  811        * This method is included for the benfit of applications that must
  812        * generate bytecodes that process method handles and {@code invokedynamic}.
  813        * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString},
  814        * because the latter requires a suitable class loader argument.
  815        * @return the bytecode type descriptor representation
  816        */
  817       public String toMethodDescriptorString() {
  818           return BytecodeDescriptor.unparse(this);
  819       }
  820   
  821       /// Serialization.
  822   
  823       /**
  824        * There are no serializable fields for {@code MethodType}.
  825        */
  826       private static final java.io.ObjectStreamField[] serialPersistentFields = { };
  827   
  828       /**
  829        * Save the {@code MethodType} instance to a stream.
  830        *
  831        * @serialData
  832        * For portability, the serialized format does not refer to named fields.
  833        * Instead, the return type and parameter type arrays are written directly
  834        * from the {@code writeObject} method, using two calls to {@code s.writeObject}
  835        * as follows:
  836        * <blockquote><pre>
  837   s.writeObject(this.returnType());
  838   s.writeObject(this.parameterArray());
  839        * </pre></blockquote>
  840        * <p>
  841        * The deserialized field values are checked as if they were
  842        * provided to the factory method {@link #methodType(Class,Class[]) methodType}.
  843        * For example, null values, or {@code void} parameter types,
  844        * will lead to exceptions during deserialization.
  845        * @param the stream to write the object to
  846        */
  847       private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
  848           s.defaultWriteObject();  // requires serialPersistentFields to be an empty array
  849           s.writeObject(returnType());
  850           s.writeObject(parameterArray());
  851       }
  852   
  853       /**
  854        * Reconstitute the {@code MethodType} instance from a stream (that is,
  855        * deserialize it).
  856        * This instance is a scratch object with bogus final fields.
  857        * It provides the parameters to the factory method called by
  858        * {@link #readResolve readResolve}.
  859        * After that call it is discarded.
  860        * @param the stream to read the object from
  861        * @see #MethodType()
  862        * @see #readResolve
  863        * @see #writeObject
  864        */
  865       private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
  866           s.defaultReadObject();  // requires serialPersistentFields to be an empty array
  867   
  868           Class<?>   returnType     = (Class<?>)   s.readObject();
  869           Class<?>[] parameterArray = (Class<?>[]) s.readObject();
  870   
  871           // Probably this object will never escape, but let's check
  872           // the field values now, just to be sure.
  873           checkRtype(returnType);
  874           checkPtypes(parameterArray);
  875   
  876           parameterArray = parameterArray.clone();  // make sure it is unshared
  877           MethodType_init(returnType, parameterArray);
  878       }
  879   
  880       /**
  881        * For serialization only.
  882        * Sets the final fields to null, pending {@code Unsafe.putObject}.
  883        */
  884       private MethodType() {
  885           this.rtype = null;
  886           this.ptypes = null;
  887       }
  888       private void MethodType_init(Class<?> rtype, Class<?>[] ptypes) {
  889           // In order to communicate these values to readResolve, we must
  890           // store them into the implementation-specific final fields.
  891           checkRtype(rtype);
  892           checkPtypes(ptypes);
  893           unsafe.putObject(this, rtypeOffset, rtype);
  894           unsafe.putObject(this, ptypesOffset, ptypes);
  895       }
  896   
  897       // Support for resetting final fields while deserializing
  898       private static final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
  899       private static final long rtypeOffset, ptypesOffset;
  900       static {
  901           try {
  902               rtypeOffset = unsafe.objectFieldOffset
  903                   (MethodType.class.getDeclaredField("rtype"));
  904               ptypesOffset = unsafe.objectFieldOffset
  905                   (MethodType.class.getDeclaredField("ptypes"));
  906           } catch (Exception ex) {
  907               throw new Error(ex);
  908           }
  909       }
  910   
  911       /**
  912        * Resolves and initializes a {@code MethodType} object
  913        * after serialization.
  914        * @return the fully initialized {@code MethodType} object
  915        */
  916       private Object readResolve() {
  917           // Do not use a trusted path for deserialization:
  918           //return makeImpl(rtype, ptypes, true);
  919           // Verify all operands, and make sure ptypes is unshared:
  920           return methodType(rtype, ptypes);
  921       }
  922   }

Home » openjdk-7 » java.lang.invoke » [javadoc | source]