1 /* 2 * Copyright (c) 2008, 2013, 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 sun.reflect.CallerSensitive; 34 import sun.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<Object>() { 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 MethodHandle cbmh = MethodHandleImpl.bindCaller(target, hostClass); 220 if (target.isVarargsCollector()) { 221 MethodType type = cbmh.type(); 222 int arity = type.parameterCount(); 223 return cbmh.asVarargsCollector(type.parameterType(arity-1)); 224 } 225 return cbmh; 226 } 227 228 /** 229 * Determines if the given object was produced by a call to {@link #asInterfaceInstance asInterfaceInstance}. 230 * @param x any reference 231 * @return true if the reference is not null and points to an object produced by {@code asInterfaceInstance} 232 */ 233 public static 234 boolean isWrapperInstance(Object x) { 235 return x instanceof WrapperInstance; 236 } 237 238 private static WrapperInstance asWrapperInstance(Object x) { 239 try { 240 if (x != null) 241 return (WrapperInstance) x; 242 } catch (ClassCastException ex) { 243 } 244 throw newIllegalArgumentException("not a wrapper instance"); 245 } 246 247 /** 248 * Produces or recovers a target method handle which is behaviorally 249 * equivalent to the unique method of this wrapper instance. 250 * The object {@code x} must have been produced by a call to {@link #asInterfaceInstance asInterfaceInstance}. 251 * This requirement may be tested via {@link #isWrapperInstance isWrapperInstance}. 252 * @param x any reference 253 * @return a method handle implementing the unique method 254 * @throws IllegalArgumentException if the reference x is not to a wrapper instance 255 */ 256 public static 257 MethodHandle wrapperInstanceTarget(Object x) { 258 return asWrapperInstance(x).getWrapperInstanceTarget(); 259 } 260 261 /** 262 * Recovers the unique single-method interface type for which this wrapper instance was created. 263 * The object {@code x} must have been produced by a call to {@link #asInterfaceInstance asInterfaceInstance}. 264 * This requirement may be tested via {@link #isWrapperInstance isWrapperInstance}. 265 * @param x any reference 266 * @return the single-method interface type for which the wrapper was created 267 * @throws IllegalArgumentException if the reference x is not to a wrapper instance 268 */ 269 public static 270 Class<?> wrapperInstanceType(Object x) { 271 return asWrapperInstance(x).getWrapperInstanceType(); 272 } 273 274 private static 275 boolean isObjectMethod(Method m) { 276 switch (m.getName()) { 277 case "toString": 278 return (m.getReturnType() == String.class 279 && m.getParameterTypes().length == 0); 280 case "hashCode": 281 return (m.getReturnType() == int.class 282 && m.getParameterTypes().length == 0); 283 case "equals": 284 return (m.getReturnType() == boolean.class 285 && m.getParameterTypes().length == 1 286 && m.getParameterTypes()[0] == Object.class); 287 } 288 return false; 289 } 290 291 private static 292 Object callObjectMethod(Object self, Method m, Object[] args) { 293 assert(isObjectMethod(m)) : m; 294 switch (m.getName()) { 295 case "toString": 296 return self.getClass().getName() + "@" + Integer.toHexString(self.hashCode()); 297 case "hashCode": 298 return System.identityHashCode(self); 299 case "equals": 300 return (self == args[0]); 301 } 302 return null; 303 } 304 305 private static 306 Method[] getSingleNameMethods(Class<?> intfc) { 307 ArrayList<Method> methods = new ArrayList<>(); 308 String uniqueName = null; 309 for (Method m : intfc.getMethods()) { 310 if (isObjectMethod(m)) continue; 311 if (!Modifier.isAbstract(m.getModifiers())) continue; 312 String mname = m.getName(); 313 if (uniqueName == null) 314 uniqueName = mname; 315 else if (!uniqueName.equals(mname)) 316 return null; // too many abstract methods 317 methods.add(m); 318 } 319 if (uniqueName == null) return null; 320 return methods.toArray(new Method[methods.size()]); 321 } 322 }