Path: blob/master/src/jdk.dynalink/share/classes/jdk/dynalink/beans/SingleDynamicMethod.java
41161 views
/*1* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file, and Oracle licenses the original version of this file under the BSD30* license:31*/32/*33Copyright 2009-2013 Attila Szegedi3435Redistribution and use in source and binary forms, with or without36modification, are permitted provided that the following conditions are37met:38* Redistributions of source code must retain the above copyright39notice, this list of conditions and the following disclaimer.40* Redistributions in binary form must reproduce the above copyright41notice, this list of conditions and the following disclaimer in the42documentation and/or other materials provided with the distribution.43* Neither the name of the copyright holder nor the names of44contributors may be used to endorse or promote products derived from45this software without specific prior written permission.4647THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS48IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED49TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A50PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER51BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR52CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF53SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR54BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,55WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR56OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF57ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.58*/5960package jdk.dynalink.beans;6162import java.lang.invoke.MethodHandle;63import java.lang.invoke.MethodHandles;64import java.lang.invoke.MethodType;65import java.lang.reflect.Array;66import java.util.StringTokenizer;67import jdk.dynalink.CallSiteDescriptor;68import jdk.dynalink.linker.LinkerServices;69import jdk.dynalink.linker.support.Guards;70import jdk.dynalink.linker.support.Lookup;7172/**73* Base class for dynamic methods that dispatch to a single target Java method or constructor. Handles adaptation of the74* target method to a call site type (including mapping variable arity methods to a call site signature with different75* arity).76*/77abstract class SingleDynamicMethod extends DynamicMethod {78private static final MethodHandle CAN_CONVERT_TO = Lookup.findOwnStatic(MethodHandles.lookup(), "canConvertTo", boolean.class, LinkerServices.class, Class.class, Object.class);7980SingleDynamicMethod(final String name) {81super(name);82}8384/**85* Returns true if this method is variable arity.86* @return true if this method is variable arity.87*/88abstract boolean isVarArgs();8990/**91* Returns this method's native type.92* @return this method's native type.93*/94abstract MethodType getMethodType();9596/**97* Given a specified call site descriptor, returns a method handle to this method's target. The target98* should only depend on the descriptor's lookup, and it should only retrieve it (as a privileged99* operation) when it is absolutely needed.100* @param desc the call site descriptor to use.101* @return the handle to this method's target method.102*/103abstract MethodHandle getTarget(CallSiteDescriptor desc);104105@Override106MethodHandle getInvocation(final CallSiteDescriptor callSiteDescriptor, final LinkerServices linkerServices) {107return linkerServices.getWithLookup(()->getInvocation(getTarget(callSiteDescriptor),108callSiteDescriptor.getMethodType(), linkerServices), callSiteDescriptor);109}110111@Override112SingleDynamicMethod getMethodForExactParamTypes(final String paramTypes) {113return typeMatchesDescription(paramTypes, getMethodType()) ? this : null;114}115116@Override117boolean contains(final SingleDynamicMethod method) {118return getMethodType().parameterList().equals(method.getMethodType().parameterList());119}120121static String getMethodNameWithSignature(final MethodType type, final String methodName, final boolean withReturnType) {122final String typeStr = type.toString();123final int retTypeIndex = typeStr.lastIndexOf(')') + 1;124int secondParamIndex = typeStr.indexOf(',') + 1;125if(secondParamIndex == 0) {126secondParamIndex = retTypeIndex - 1;127}128final StringBuilder b = new StringBuilder();129if (withReturnType) {130b.append(typeStr, retTypeIndex, typeStr.length()).append(' ');131}132return b.append(methodName).append('(').append(typeStr, secondParamIndex, retTypeIndex).toString();133}134135/**136* Given a method handle and a call site type, adapts the method handle to the call site type. Performs type137* conversions as needed using the specified linker services, and in case that the method handle is a vararg138* collector, matches it to the arity of the call site. The type of the return value is only changed if it can be139* converted using a conversion that loses neither precision nor magnitude, see140* {@link LinkerServices#asTypeLosslessReturn(MethodHandle, MethodType)}.141* @param target the method handle to adapt142* @param callSiteType the type of the call site143* @param linkerServices the linker services used for type conversions144* @return the adapted method handle.145*/146static MethodHandle getInvocation(final MethodHandle target, final MethodType callSiteType, final LinkerServices linkerServices) {147final MethodHandle filteredTarget = linkerServices.filterInternalObjects(target);148final MethodType methodType = filteredTarget.type();149final int paramsLen = methodType.parameterCount();150final boolean varArgs = target.isVarargsCollector();151final MethodHandle fixTarget = varArgs ? filteredTarget.asFixedArity() : filteredTarget;152final int fixParamsLen = varArgs ? paramsLen - 1 : paramsLen;153final int argsLen = callSiteType.parameterCount();154if(argsLen < fixParamsLen) {155// Less actual arguments than number of fixed declared arguments; can't invoke.156return null;157}158// Method handle has the same number of fixed arguments as the call site type159if(argsLen == fixParamsLen) {160// Method handle that matches the number of actual arguments as the number of fixed arguments161final MethodHandle matchedMethod;162if(varArgs) {163// If vararg, add a zero-length array of the expected type as the last argument to signify no variable164// arguments.165matchedMethod = MethodHandles.insertArguments(fixTarget, fixParamsLen, Array.newInstance(166methodType.parameterType(fixParamsLen).getComponentType(), 0));167} else {168// Otherwise, just use the method169matchedMethod = fixTarget;170}171return createConvertingInvocation(matchedMethod, linkerServices, callSiteType);172}173174// What's below only works for varargs175if(!varArgs) {176return null;177}178179final Class<?> varArgType = methodType.parameterType(fixParamsLen);180// Handle a somewhat sinister corner case: caller passes exactly one argument in the vararg position, and we181// must handle both a prepacked vararg array as well as a genuine 1-long vararg sequence.182if(argsLen == paramsLen) {183final Class<?> callSiteLastArgType = callSiteType.parameterType(fixParamsLen);184if(varArgType.isAssignableFrom(callSiteLastArgType)) {185// Call site signature guarantees we'll always be passed a single compatible array; just link directly186// to the method, introducing necessary conversions. Also, preserve it being a variable arity method.187return createConvertingInvocation(filteredTarget, linkerServices, callSiteType).asVarargsCollector(188callSiteLastArgType);189}190191// This method handle takes the single argument and packs it into a newly allocated single-element array. It192// will be used when the incoming argument can't be converted to the vararg array type (the "vararg packer"193// method).194final MethodHandle varArgCollectingInvocation = createConvertingInvocation(collectArguments(fixTarget,195argsLen), linkerServices, callSiteType);196197// Is call site type assignable from an array type (e.g. Object:int[], or Object[]:String[])198final boolean isAssignableFromArray = callSiteLastArgType.isAssignableFrom(varArgType);199// Do we have a custom conversion that can potentially convert the call site type to an array?200final boolean isCustomConvertible = linkerServices.canConvert(callSiteLastArgType, varArgType);201if(!isAssignableFromArray && !isCustomConvertible) {202// Call site signature guarantees the argument can definitely not be converted to an array (i.e. it is203// primitive), and no conversion can help with it either. Link immediately to a vararg-packing method204// handle.205return varArgCollectingInvocation;206}207208// This method handle employs language-specific conversions to convert the last argument into an array of209// vararg type.210final MethodHandle arrayConvertingInvocation = createConvertingInvocation(MethodHandles.filterArguments(211fixTarget, fixParamsLen, linkerServices.getTypeConverter(callSiteLastArgType, varArgType)),212linkerServices, callSiteType);213214// This method handle determines whether the value can be converted to the array of vararg type using a215// language-specific conversion.216final MethodHandle canConvertArgToArray = MethodHandles.insertArguments(CAN_CONVERT_TO, 0, linkerServices,217varArgType);218219// This one adjusts the previous one for the location of the argument and the call site type.220final MethodHandle canConvertLastArgToArray = MethodHandles.dropArguments(canConvertArgToArray, 0,221MethodType.genericMethodType(fixParamsLen).parameterList()).asType(callSiteType.changeReturnType(boolean.class));222223// This one takes the previous ones and combines them into a method handle that converts the argument into224// a vararg array when it can, otherwise falls back to the vararg packer.225final MethodHandle convertToArrayWhenPossible = MethodHandles.guardWithTest(canConvertLastArgToArray,226arrayConvertingInvocation, varArgCollectingInvocation);227228if(isAssignableFromArray) {229return MethodHandles.guardWithTest(230// Is incoming parameter already a compatible array?231Guards.isInstance(varArgType, fixParamsLen, callSiteType),232// Yes: just pass it to the method233createConvertingInvocation(fixTarget, linkerServices, callSiteType),234// No: either go through a custom conversion, or if it is not possible, go directly to the235// vararg packer.236isCustomConvertible ? convertToArrayWhenPossible : varArgCollectingInvocation);237}238239// Just do the custom conversion with fallback to the vararg packer logic.240assert isCustomConvertible;241return convertToArrayWhenPossible;242}243244// Remaining case: more than one vararg.245return createConvertingInvocation(collectArguments(fixTarget, argsLen), linkerServices, callSiteType);246}247248@SuppressWarnings("unused")249private static boolean canConvertTo(final LinkerServices linkerServices, final Class<?> to, final Object obj) {250return obj != null && linkerServices.canConvert(obj.getClass(), to);251}252253/**254* Creates a method handle out of the original target that will collect the varargs for the exact component type of255* the varArg array. Note that this will nicely trigger language-specific type converters for exactly those varargs256* for which it is necessary when later passed to linkerServices.convertArguments().257*258* @param target the original method handle259* @param parameterCount the total number of arguments in the new method handle260* @return a collecting method handle261*/262static MethodHandle collectArguments(final MethodHandle target, final int parameterCount) {263final MethodType methodType = target.type();264final int fixParamsLen = methodType.parameterCount() - 1;265final Class<?> arrayType = methodType.parameterType(fixParamsLen);266return target.asCollector(arrayType, parameterCount - fixParamsLen);267}268269private static MethodHandle createConvertingInvocation(final MethodHandle sizedMethod,270final LinkerServices linkerServices, final MethodType callSiteType) {271return linkerServices.asTypeLosslessReturn(sizedMethod, callSiteType);272}273274private static boolean typeMatchesDescription(final String paramTypes, final MethodType type) {275final StringTokenizer tok = new StringTokenizer(paramTypes, ", ");276for(int i = 1; i < type.parameterCount(); ++i) { // i = 1 as we ignore the receiver277if(!(tok.hasMoreTokens() && typeNameMatches(tok.nextToken(), type.parameterType(i)))) {278return false;279}280}281return !tok.hasMoreTokens();282}283284private static boolean typeNameMatches(final String typeName, final Class<?> type) {285return typeName.equals(typeName.indexOf('.') == -1 ? type.getSimpleName() : type.getCanonicalName());286}287}288289290