1 /* 2 * Copyright (c) 2008, 2016, 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 java.lang.reflect.*; 29 import java.security.AccessController; 30 import java.security.PrivilegedAction; 31 import sun.invoke.WrapperInstance; 32 import java.util.ArrayList; 33 import jdk.internal.reflect.CallerSensitive; 34 import jdk.internal.reflect.Reflection; 35 import sun.reflect.misc.ReflectUtil; 36 import static java.lang.invoke.MethodHandleStatics.*; 37 38 /** 39 * This class consists exclusively of static methods that help adapt 40 * method handles to other JVM types, such as interfaces. 41 */ 42 public class MethodHandleProxies { 43 44 private MethodHandleProxies() { } // do not instantiate 45 46 /** 47 * Produces an instance of the given single-method interface which redirects 48 * its calls to the given method handle. 49 * <p> 50 * A single-method interface is an interface which declares a uniquely named method. 51 * When determining the uniquely named method of a single-method interface, 52 * the public {@code Object} methods ({@code toString}, {@code equals}, {@code hashCode}) 53 * are disregarded. For example, {@link java.util.Comparator} is a single-method interface, 54 * even though it re-declares the {@code Object.equals} method. 55 * <p> 56 * The interface must be public. No additional access checks are performed. 57 * <p> 58 * The resulting instance of the required type will respond to 59 * invocation of the type's uniquely named method by calling 60 * the given target on the incoming arguments, 61 * and returning or throwing whatever the target 62 * returns or throws. The invocation will be as if by 63 * {@code target.invoke}. 64 * The target's type will be checked before the 65 * instance is created, as if by a call to {@code asType}, 66 * which may result in a {@code WrongMethodTypeException}. 67 * <p> 68 * The uniquely named method is allowed to be multiply declared, 69 * with distinct type descriptors. (E.g., it can be overloaded, 70 * or can possess bridge methods.) All such declarations are 71 * connected directly to the target method handle. 72 * Argument and return types are adjusted by {@code asType} 73 * for each individual declaration. 74 * <p> 75 * The wrapper instance will implement the requested interface 76 * and its super-types, but no other single-method interfaces. 77 * This means that the instance will not unexpectedly 78 * pass an {@code instanceof} test for any unrequested type. 79 * <p style="font-size:smaller;"> 80 * <em>Implementation Note:</em> 81 * Therefore, each instance must implement a unique single-method interface. 82 * Implementations may not bundle together 83 * multiple single-method interfaces onto single implementation classes 84 * in the style of {@link java.awt.AWTEventMulticaster}. 85 * <p> 86 * The method handle may throw an <em>undeclared exception</em>, 87 * which means any checked exception (or other checked throwable) 88 * not declared by the requested type's single abstract method. 89 * If this happens, the throwable will be wrapped in an instance of 90 * {@link java.lang.reflect.UndeclaredThrowableException UndeclaredThrowableException} 91 * and thrown in that wrapped form. 92 * <p> 93 * Like {@link java.lang.Integer#valueOf Integer.valueOf}, 94 * {@code asInterfaceInstance} is a factory method whose results are defined 95 * by their behavior. 96 * It is not guaranteed to return a new instance for every call. 97 * <p> 98 * Because of the possibility of {@linkplain java.lang.reflect.Method#isBridge bridge methods} 99 * and other corner cases, the interface may also have several abstract methods 100 * with the same name but having distinct descriptors (types of returns and parameters). 101 * In this case, all the methods are bound in common to the one given target. 102 * The type check and effective {@code asType} conversion is applied to each 103 * method type descriptor, and all abstract methods are bound to the target in common. 104 * Beyond this type check, no further checks are made to determine that the 105 * abstract methods are related in any way. 106 * <p> 107 * Future versions of this API may accept additional types, 108 * such as abstract classes with single abstract methods. 109 * Future versions of this API may also equip wrapper instances 110 * with one or more additional public "marker" interfaces. 111 * <p> 112 * If a security manager is installed, this method is caller sensitive. 113 * During any invocation of the target method handle via the returned wrapper, 114 * the original creator of the wrapper (the caller) will be visible 115 * to context checks requested by the security manager. 116 * 117 * @param <T> the desired type of the wrapper, a single-method interface 118 * @param intfc a class object representing {@code T} 119 * @param target the method handle to invoke from the wrapper 120 * @return a correctly-typed wrapper for the given target 121 * @throws NullPointerException if either argument is null 122 * @throws IllegalArgumentException if the {@code intfc} is not a 123 * valid argument to this method 124 * @throws WrongMethodTypeException if the target cannot 125 * be converted to the type required by the requested interface 126 */ 127 // Other notes to implementors: 128 // <p> 129 // No stable mapping is promised between the single-method interface and 130 // the implementation class C. Over time, several implementation 131 // classes might be used for the same type. 132 // <p> 133 // If the implementation is able 134 // to prove that a wrapper of the required type 135 // has already been created for a given 136 // method handle, or for another method handle with the 137 // same behavior, the implementation may return that wrapper in place of 138 // a new wrapper. 139 // <p> 140 // This method is designed to apply to common use cases 141 // where a single method handle must interoperate with 142 // an interface that implements a function-like 143 // API. Additional variations, such as single-abstract-method classes with 144 // private constructors, or interfaces with multiple but related 145 // entry points, must be covered by hand-written or automatically 146 // generated adapter classes. 147 // 148 @CallerSensitive 149 public static 150 <T> T asInterfaceInstance(final Class<T> intfc, final MethodHandle target) { 151 if (!intfc.isInterface() || !Modifier.isPublic(intfc.getModifiers())) 152 throw newIllegalArgumentException("not a public interface", intfc.getName()); 153 final MethodHandle mh; 154 if (System.getSecurityManager() != null) { 155 final Class<?> caller = Reflection.getCallerClass(); 156 final ClassLoader ccl = caller != null ? caller.getClassLoader() : null; 157 ReflectUtil.checkProxyPackageAccess(ccl, intfc); 158 mh = ccl != null ? bindCaller(target, caller) : target; 159 } else { 160 mh = target; 161 } 162 ClassLoader proxyLoader = intfc.getClassLoader(); 163 if (proxyLoader == null) { 164 ClassLoader cl = Thread.currentThread().getContextClassLoader(); // avoid use of BCP 165 proxyLoader = cl != null ? cl : ClassLoader.getSystemClassLoader(); 166 } 167 final Method[] methods = getSingleNameMethods(intfc); 168 if (methods == null) 169 throw newIllegalArgumentException("not a single-method interface", intfc.getName()); 170 final MethodHandle[] vaTargets = new MethodHandle[methods.length]; 171 for (int i = 0; i < methods.length; i++) { 172 Method sm = methods[i]; 173 MethodType smMT = MethodType.methodType(sm.getReturnType(), sm.getParameterTypes()); 174 MethodHandle checkTarget = mh.asType(smMT); // make throw WMT 175 checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class)); 176 vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount()); 177 } 178 final InvocationHandler ih = new InvocationHandler() { 179 private Object getArg(String name) { 180 if ((Object)name == "getWrapperInstanceTarget") return target; 181 if ((Object)name == "getWrapperInstanceType") return intfc; 182 throw new AssertionError(); 183 } 184 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 185 for (int i = 0; i < methods.length; i++) { 186 if (method.equals(methods[i])) 187 return vaTargets[i].invokeExact(args); 188 } 189 if (method.getDeclaringClass() == WrapperInstance.class) 190 return getArg(method.getName()); 191 if (isObjectMethod(method)) 192 return callObjectMethod(proxy, method, args); 193 throw newInternalError("bad proxy method: "+method); 194 } 195 }; 196 197 final Object proxy; 198 if (System.getSecurityManager() != null) { 199 // sun.invoke.WrapperInstance is a restricted interface not accessible 200 // by any non-null class loader. 201 final ClassLoader loader = proxyLoader; 202 proxy = AccessController.doPrivileged(new PrivilegedAction<>() { 203 public Object run() { 204 return Proxy.newProxyInstance( 205 loader, 206 new Class<?>[]{ intfc, WrapperInstance.class }, 207 ih); 208 } 209 }); 210 } else { 211 proxy = Proxy.newProxyInstance(proxyLoader, 212 new Class<?>[]{ intfc, WrapperInstance.class }, 213 ih); 214 } 215 return intfc.cast(proxy); 216 } 217 218 private static MethodHandle bindCaller(MethodHandle target, Class<?> hostClass) { 219 return MethodHandleImpl.bindCaller(target, hostClass).withVarargs(target.isVarargsCollector()); 220 } 221 222 /** 223 * Determines if the given object was produced by a call to {@link #asInterfaceInstance asInterfaceInstance}. 224 * @param x any reference 225 * @return true if the reference is not null and points to an object produced by {@code asInterfaceInstance} 226 */ 227 public static 228 boolean isWrapperInstance(Object x) { 229 return x instanceof WrapperInstance; 230 } 231 232 private static WrapperInstance asWrapperInstance(Object x) { 233 try { 234 if (x != null) 235 return (WrapperInstance) x; 236 } catch (ClassCastException ex) { 237 } 238 throw newIllegalArgumentException("not a wrapper instance"); 239 } 240 241 /** 242 * Produces or recovers a target method handle which is behaviorally 243 * equivalent to the unique method of this wrapper instance. 244 * The object {@code x} must have been produced by a call to {@link #asInterfaceInstance asInterfaceInstance}. 245 * This requirement may be tested via {@link #isWrapperInstance isWrapperInstance}. 246 * @param x any reference 247 * @return a method handle implementing the unique method 248 * @throws IllegalArgumentException if the reference x is not to a wrapper instance 249 */ 250 public static 251 MethodHandle wrapperInstanceTarget(Object x) { 252 return asWrapperInstance(x).getWrapperInstanceTarget(); 253 } 254 255 /** 256 * Recovers the unique single-method interface type for which this wrapper instance was created. 257 * The object {@code x} must have been produced by a call to {@link #asInterfaceInstance asInterfaceInstance}. 258 * This requirement may be tested via {@link #isWrapperInstance isWrapperInstance}. 259 * @param x any reference 260 * @return the single-method interface type for which the wrapper was created 261 * @throws IllegalArgumentException if the reference x is not to a wrapper instance 262 */ 263 public static 264 Class<?> wrapperInstanceType(Object x) { 265 return asWrapperInstance(x).getWrapperInstanceType(); 266 } 267 268 private static 269 boolean isObjectMethod(Method m) { 270 switch (m.getName()) { 271 case "toString": 272 return (m.getReturnType() == String.class 273 && m.getParameterTypes().length == 0); 274 case "hashCode": 275 return (m.getReturnType() == int.class 276 && m.getParameterTypes().length == 0); 277 case "equals": 278 return (m.getReturnType() == boolean.class 279 && m.getParameterTypes().length == 1 280 && m.getParameterTypes()[0] == Object.class); 281 } 282 return false; 283 } 284 285 private static 286 Object callObjectMethod(Object self, Method m, Object[] args) { 287 assert(isObjectMethod(m)) : m; 288 switch (m.getName()) { 289 case "toString": 290 return self.getClass().getName() + "@" + Integer.toHexString(self.hashCode()); 291 case "hashCode": 292 return System.identityHashCode(self); 293 case "equals": 294 return (self == args[0]); 295 } 296 return null; 297 } 298 299 private static 300 Method[] getSingleNameMethods(Class<?> intfc) { 301 ArrayList<Method> methods = new ArrayList<>(); 302 String uniqueName = null; 303 for (Method m : intfc.getMethods()) { 304 if (isObjectMethod(m)) continue; 305 if (!Modifier.isAbstract(m.getModifiers())) continue; 306 String mname = m.getName(); 307 if (uniqueName == null) 308 uniqueName = mname; 309 else if (!uniqueName.equals(mname)) 310 return null; // too many abstract methods 311 methods.add(m); 312 } 313 if (uniqueName == null) return null; 314 return methods.toArray(new Method[methods.size()]); 315 } 316 }