Path: blob/master/src/jdk.dynalink/share/classes/jdk/dynalink/beans/OverloadedMethod.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.util.ArrayList;66import java.util.Iterator;67import java.util.List;68import java.util.Map;69import java.util.concurrent.ConcurrentHashMap;70import jdk.dynalink.SecureLookupSupplier;71import jdk.dynalink.internal.InternalTypeUtilities;72import jdk.dynalink.linker.LinkerServices;73import jdk.dynalink.linker.support.Lookup;7475/**76* Represents a subset of overloaded methods for a certain method name on a certain class. It can be either a fixarg or77* a vararg subset depending on the subclass. The method is for a fixed number of arguments though (as it is generated78* for a concrete call site). As such, all methods in the subset can be invoked with the specified number of arguments79* (exactly matching for fixargs, or having less than or equal fixed arguments, for varargs).80*/81class OverloadedMethod {82private final Map<ClassString, MethodHandle> argTypesToMethods = new ConcurrentHashMap<>();83private final OverloadedDynamicMethod parent;84private final ClassLoader callSiteClassLoader;85private final MethodType callSiteType;86private final MethodHandle invoker;87private final LinkerServices linkerServices;88private final SecureLookupSupplier lookupSupplier;89private final ArrayList<MethodHandle> fixArgMethods;90private final ArrayList<MethodHandle> varArgMethods;9192OverloadedMethod(final List<MethodHandle> methodHandles,93final OverloadedDynamicMethod parent,94final ClassLoader callSiteClassLoader,95final MethodType callSiteType,96final LinkerServices linkerServices,97final SecureLookupSupplier lookupSupplier) {98this.parent = parent;99this.callSiteClassLoader = callSiteClassLoader;100final Class<?> commonRetType = getCommonReturnType(methodHandles);101this.callSiteType = callSiteType.changeReturnType(commonRetType);102this.linkerServices = linkerServices;103this.lookupSupplier = lookupSupplier;104105fixArgMethods = new ArrayList<>(methodHandles.size());106varArgMethods = new ArrayList<>(methodHandles.size());107final int argNum = callSiteType.parameterCount();108for(final MethodHandle mh: methodHandles) {109if(mh.isVarargsCollector()) {110final MethodHandle asFixed = mh.asFixedArity();111if(argNum == asFixed.type().parameterCount()) {112fixArgMethods.add(asFixed);113}114varArgMethods.add(mh);115} else {116fixArgMethods.add(mh);117}118}119fixArgMethods.trimToSize();120varArgMethods.trimToSize();121122final MethodHandle bound = SELECT_METHOD.bindTo(this);123final MethodHandle collecting = SingleDynamicMethod.collectArguments(bound, argNum).asType(124callSiteType.changeReturnType(MethodHandle.class));125invoker = linkerServices.asTypeLosslessReturn(MethodHandles.foldArguments(126MethodHandles.exactInvoker(this.callSiteType), collecting), callSiteType);127}128129MethodHandle getInvoker() {130return invoker;131}132133private static final MethodHandle SELECT_METHOD = Lookup.findOwnSpecial(MethodHandles.lookup(), "selectMethod",134MethodHandle.class, Object[].class);135136@SuppressWarnings("unused")137private MethodHandle selectMethod(final Object[] args) {138final Class<?>[] argTypes = new Class<?>[args.length];139for(int i = 0; i < argTypes.length; ++i) {140final Object arg = args[i];141argTypes[i] = arg == null ? ClassString.NULL_CLASS : arg.getClass();142}143final ClassString classString = new ClassString(argTypes);144MethodHandle method = argTypesToMethods.get(classString);145if(method == null) {146List<MethodHandle> methods = classString.getMaximallySpecifics(fixArgMethods, linkerServices, false);147if(methods.isEmpty()) {148methods = classString.getMaximallySpecifics(varArgMethods, linkerServices, true);149}150switch(methods.size()) {151case 0: {152method = getNoSuchMethodThrower(argTypes);153break;154}155case 1: {156final List<MethodHandle> fmethods = methods;157method = linkerServices.getWithLookup(158()->SingleDynamicMethod.getInvocation(fmethods.get(0), callSiteType, linkerServices),159lookupSupplier);160break;161}162default: {163// This is unfortunate - invocation time ambiguity.164method = getAmbiguousMethodThrower(argTypes, methods);165break;166}167}168// Avoid keeping references to unrelated classes; this ruins the169// performance a bit, but avoids class loader memory leaks.170if(classString.isVisibleFrom(callSiteClassLoader)) {171argTypesToMethods.put(classString, method);172}173}174return method;175}176177private MethodHandle getNoSuchMethodThrower(final Class<?>[] argTypes) {178return adaptThrower(MethodHandles.insertArguments(THROW_NO_SUCH_METHOD, 0, this, argTypes));179}180181private static final MethodHandle THROW_NO_SUCH_METHOD = Lookup.findOwnSpecial(MethodHandles.lookup(),182"throwNoSuchMethod", void.class, Class[].class);183184@SuppressWarnings("unused")185private void throwNoSuchMethod(final Class<?>[] argTypes) throws NoSuchMethodException {186if(varArgMethods.isEmpty()) {187throw new NoSuchMethodException("None of the fixed arity signatures " + getSignatureList(fixArgMethods) +188" of method " + parent.getName() + " match the argument types " + argTypesString(argTypes));189}190throw new NoSuchMethodException("None of the fixed arity signatures " + getSignatureList(fixArgMethods) +191" or the variable arity signatures " + getSignatureList(varArgMethods) + " of the method " +192parent.getName() + " match the argument types " + argTypesString(argTypes));193}194195private MethodHandle getAmbiguousMethodThrower(final Class<?>[] argTypes, final List<MethodHandle> methods) {196return adaptThrower(MethodHandles.insertArguments(THROW_AMBIGUOUS_METHOD, 0, this, argTypes, methods));197}198199private MethodHandle adaptThrower(final MethodHandle rawThrower) {200return MethodHandles.dropArguments(rawThrower, 0, callSiteType.parameterList()).asType(callSiteType);201}202203private static final MethodHandle THROW_AMBIGUOUS_METHOD = Lookup.findOwnSpecial(MethodHandles.lookup(),204"throwAmbiguousMethod", void.class, Class[].class, List.class);205206@SuppressWarnings("unused")207private void throwAmbiguousMethod(final Class<?>[] argTypes, final List<MethodHandle> methods) throws NoSuchMethodException {208final String arity = methods.get(0).isVarargsCollector() ? "variable" : "fixed";209throw new NoSuchMethodException("Can't unambiguously select between " + arity + " arity signatures " +210getSignatureList(methods) + " of the method " + parent.getName() + " for argument types " +211argTypesString(argTypes));212}213214private static String argTypesString(final Class<?>[] classes) {215final StringBuilder b = new StringBuilder().append('[');216appendTypes(b, classes, false);217return b.append(']').toString();218}219220private static String getSignatureList(final List<MethodHandle> methods) {221final StringBuilder b = new StringBuilder().append('[');222final Iterator<MethodHandle> it = methods.iterator();223if(it.hasNext()) {224appendSig(b, it.next());225while(it.hasNext()) {226appendSig(b.append(", "), it.next());227}228}229return b.append(']').toString();230}231232private static void appendSig(final StringBuilder b, final MethodHandle m) {233b.append('(');234appendTypes(b, m.type().parameterArray(), m.isVarargsCollector());235b.append(')');236}237238private static void appendTypes(final StringBuilder b, final Class<?>[] classes, final boolean varArg) {239final int l = classes.length;240if(!varArg) {241if(l > 1) {242b.append(classes[1].getCanonicalName());243for(int i = 2; i < l; ++i) {244b.append(", ").append(classes[i].getCanonicalName());245}246}247} else {248for(int i = 1; i < l - 1; ++i) {249b.append(classes[i].getCanonicalName()).append(", ");250}251b.append(classes[l - 1].getComponentType().getCanonicalName()).append("...");252}253}254255private static Class<?> getCommonReturnType(final List<MethodHandle> methodHandles) {256final Iterator<MethodHandle> it = methodHandles.iterator();257Class<?> retType = it.next().type().returnType();258while(it.hasNext()) {259retType = InternalTypeUtilities.getCommonLosslessConversionType(retType, it.next().type().returnType());260}261return retType;262}263}264265266