1 /* 2 * Copyright (c) 1999, 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.reflect; 27 28 import java.lang.ref.WeakReference; 29 import java.security.AccessController; 30 import java.security.PrivilegedAction; 31 import java.util.Arrays; 32 import java.util.IdentityHashMap; 33 import java.util.Map; 34 import java.util.concurrent.atomic.AtomicLong; 35 import java.util.function.BiFunction; 36 import sun.misc.ProxyGenerator; 37 import sun.misc.VM; 38 import sun.reflect.CallerSensitive; 39 import sun.reflect.Reflection; 40 import sun.reflect.misc.ReflectUtil; 41 import sun.security.util.SecurityConstants; 42 43 /** 44 * {@code Proxy} provides static methods for creating dynamic proxy 45 * classes and instances, and it is also the superclass of all 46 * dynamic proxy classes created by those methods. 47 * 48 * <p>To create a proxy for some interface {@code Foo}: 49 * <pre> 50 * InvocationHandler handler = new MyInvocationHandler(...); 51 * Class<?> proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(), Foo.class); 52 * Foo f = (Foo) proxyClass.getConstructor(InvocationHandler.class). 53 * newInstance(handler); 54 * </pre> 55 * or more simply: 56 * <pre> 57 * Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), 58 * new Class<?>[] { Foo.class }, 59 * handler); 60 * </pre> 61 * 62 * <p>A <i>dynamic proxy class</i> (simply referred to as a <i>proxy 63 * class</i> below) is a class that implements a list of interfaces 64 * specified at runtime when the class is created, with behavior as 65 * described below. 66 * 67 * A <i>proxy interface</i> is such an interface that is implemented 68 * by a proxy class. 69 * 70 * A <i>proxy instance</i> is an instance of a proxy class. 71 * 72 * Each proxy instance has an associated <i>invocation handler</i> 73 * object, which implements the interface {@link InvocationHandler}. 74 * A method invocation on a proxy instance through one of its proxy 75 * interfaces will be dispatched to the {@link InvocationHandler#invoke 76 * invoke} method of the instance's invocation handler, passing the proxy 77 * instance, a {@code java.lang.reflect.Method} object identifying 78 * the method that was invoked, and an array of type {@code Object} 79 * containing the arguments. The invocation handler processes the 80 * encoded method invocation as appropriate and the result that it 81 * returns will be returned as the result of the method invocation on 82 * the proxy instance. 83 * 84 * <p>A proxy class has the following properties: 85 * 86 * <ul> 87 * <li>Proxy classes are <em>public, final, and not abstract</em> if 88 * all proxy interfaces are public.</li> 89 * 90 * <li>Proxy classes are <em>non-public, final, and not abstract</em> if 91 * any of the proxy interfaces is non-public.</li> 92 * 93 * <li>The unqualified name of a proxy class is unspecified. The space 94 * of class names that begin with the string {@code "$Proxy"} 95 * should be, however, reserved for proxy classes. 96 * 97 * <li>A proxy class extends {@code java.lang.reflect.Proxy}. 98 * 99 * <li>A proxy class implements exactly the interfaces specified at its 100 * creation, in the same order. 101 * 102 * <li>If a proxy class implements a non-public interface, then it will 103 * be defined in the same package as that interface. Otherwise, the 104 * package of a proxy class is also unspecified. Note that package 105 * sealing will not prevent a proxy class from being successfully defined 106 * in a particular package at runtime, and neither will classes already 107 * defined by the same class loader and the same package with particular 108 * signers. 109 * 110 * <li>Since a proxy class implements all of the interfaces specified at 111 * its creation, invoking {@code getInterfaces} on its 112 * {@code Class} object will return an array containing the same 113 * list of interfaces (in the order specified at its creation), invoking 114 * {@code getMethods} on its {@code Class} object will return 115 * an array of {@code Method} objects that include all of the 116 * methods in those interfaces, and invoking {@code getMethod} will 117 * find methods in the proxy interfaces as would be expected. 118 * 119 * <li>The {@link Proxy#isProxyClass Proxy.isProxyClass} method will 120 * return true if it is passed a proxy class-- a class returned by 121 * {@code Proxy.getProxyClass} or the class of an object returned by 122 * {@code Proxy.newProxyInstance}-- and false otherwise. 123 * 124 * <li>The {@code java.security.ProtectionDomain} of a proxy class 125 * is the same as that of system classes loaded by the bootstrap class 126 * loader, such as {@code java.lang.Object}, because the code for a 127 * proxy class is generated by trusted system code. This protection 128 * domain will typically be granted 129 * {@code java.security.AllPermission}. 130 * 131 * <li>Each proxy class has one public constructor that takes one argument, 132 * an implementation of the interface {@link InvocationHandler}, to set 133 * the invocation handler for a proxy instance. Rather than having to use 134 * the reflection API to access the public constructor, a proxy instance 135 * can be also be created by calling the {@link Proxy#newProxyInstance 136 * Proxy.newProxyInstance} method, which combines the actions of calling 137 * {@link Proxy#getProxyClass Proxy.getProxyClass} with invoking the 138 * constructor with an invocation handler. 139 * </ul> 140 * 141 * <p>A proxy instance has the following properties: 142 * 143 * <ul> 144 * <li>Given a proxy instance {@code proxy} and one of the 145 * interfaces implemented by its proxy class {@code Foo}, the 146 * following expression will return true: 147 * <pre> 148 * {@code proxy instanceof Foo} 149 * </pre> 150 * and the following cast operation will succeed (rather than throwing 151 * a {@code ClassCastException}): 152 * <pre> 153 * {@code (Foo) proxy} 154 * </pre> 155 * 156 * <li>Each proxy instance has an associated invocation handler, the one 157 * that was passed to its constructor. The static 158 * {@link Proxy#getInvocationHandler Proxy.getInvocationHandler} method 159 * will return the invocation handler associated with the proxy instance 160 * passed as its argument. 161 * 162 * <li>An interface method invocation on a proxy instance will be 163 * encoded and dispatched to the invocation handler's {@link 164 * InvocationHandler#invoke invoke} method as described in the 165 * documentation for that method. 166 * 167 * <li>An invocation of the {@code hashCode}, 168 * {@code equals}, or {@code toString} methods declared in 169 * {@code java.lang.Object} on a proxy instance will be encoded and 170 * dispatched to the invocation handler's {@code invoke} method in 171 * the same manner as interface method invocations are encoded and 172 * dispatched, as described above. The declaring class of the 173 * {@code Method} object passed to {@code invoke} will be 174 * {@code java.lang.Object}. Other public methods of a proxy 175 * instance inherited from {@code java.lang.Object} are not 176 * overridden by a proxy class, so invocations of those methods behave 177 * like they do for instances of {@code java.lang.Object}. 178 * </ul> 179 * 180 * <h3>Methods Duplicated in Multiple Proxy Interfaces</h3> 181 * 182 * <p>When two or more interfaces of a proxy class contain a method with 183 * the same name and parameter signature, the order of the proxy class's 184 * interfaces becomes significant. When such a <i>duplicate method</i> 185 * is invoked on a proxy instance, the {@code Method} object passed 186 * to the invocation handler will not necessarily be the one whose 187 * declaring class is assignable from the reference type of the interface 188 * that the proxy's method was invoked through. This limitation exists 189 * because the corresponding method implementation in the generated proxy 190 * class cannot determine which interface it was invoked through. 191 * Therefore, when a duplicate method is invoked on a proxy instance, 192 * the {@code Method} object for the method in the foremost interface 193 * that contains the method (either directly or inherited through a 194 * superinterface) in the proxy class's list of interfaces is passed to 195 * the invocation handler's {@code invoke} method, regardless of the 196 * reference type through which the method invocation occurred. 197 * 198 * <p>If a proxy interface contains a method with the same name and 199 * parameter signature as the {@code hashCode}, {@code equals}, 200 * or {@code toString} methods of {@code java.lang.Object}, 201 * when such a method is invoked on a proxy instance, the 202 * {@code Method} object passed to the invocation handler will have 203 * {@code java.lang.Object} as its declaring class. In other words, 204 * the public, non-final methods of {@code java.lang.Object} 205 * logically precede all of the proxy interfaces for the determination of 206 * which {@code Method} object to pass to the invocation handler. 207 * 208 * <p>Note also that when a duplicate method is dispatched to an 209 * invocation handler, the {@code invoke} method may only throw 210 * checked exception types that are assignable to one of the exception 211 * types in the {@code throws} clause of the method in <i>all</i> of 212 * the proxy interfaces that it can be invoked through. If the 213 * {@code invoke} method throws a checked exception that is not 214 * assignable to any of the exception types declared by the method in one 215 * of the proxy interfaces that it can be invoked through, then an 216 * unchecked {@code UndeclaredThrowableException} will be thrown by 217 * the invocation on the proxy instance. This restriction means that not 218 * all of the exception types returned by invoking 219 * {@code getExceptionTypes} on the {@code Method} object 220 * passed to the {@code invoke} method can necessarily be thrown 221 * successfully by the {@code invoke} method. 222 * 223 * @author Peter Jones 224 * @see InvocationHandler 225 * @since 1.3 226 */ 227 public class Proxy implements java.io.Serializable { 228 229 private static final long serialVersionUID = -2222568056686623797L; 230 231 /** parameter types of a proxy class constructor */ 232 private static final Class<?>[] constructorParams = 233 { InvocationHandler.class }; 234 235 /** 236 * a cache of proxy classes 237 */ 238 private static final WeakCache<ClassLoader, Class<?>[], Class<?>> 239 proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory()); 240 241 /** 242 * the invocation handler for this proxy instance. 243 * @serial 244 */ 245 protected InvocationHandler h; 246 247 /** 248 * Prohibits instantiation. 249 */ 250 private Proxy() { 251 } 252 253 /** 254 * Constructs a new {@code Proxy} instance from a subclass 255 * (typically, a dynamic proxy class) with the specified value 256 * for its invocation handler. 257 * 258 * @param h the invocation handler for this proxy instance 259 */ 260 protected Proxy(InvocationHandler h) { 261 this.h = h; 262 } 263 264 /** 265 * Returns the {@code java.lang.Class} object for a proxy class 266 * given a class loader and an array of interfaces. The proxy class 267 * will be defined by the specified class loader and will implement 268 * all of the supplied interfaces. If any of the given interfaces 269 * is non-public, the proxy class will be non-public. If a proxy class 270 * for the same permutation of interfaces has already been defined by the 271 * class loader, then the existing proxy class will be returned; otherwise, 272 * a proxy class for those interfaces will be generated dynamically 273 * and defined by the class loader. 274 * 275 * <p>There are several restrictions on the parameters that may be 276 * passed to {@code Proxy.getProxyClass}: 277 * 278 * <ul> 279 * <li>All of the {@code Class} objects in the 280 * {@code interfaces} array must represent interfaces, not 281 * classes or primitive types. 282 * 283 * <li>No two elements in the {@code interfaces} array may 284 * refer to identical {@code Class} objects. 285 * 286 * <li>All of the interface types must be visible by name through the 287 * specified class loader. In other words, for class loader 288 * {@code cl} and every interface {@code i}, the following 289 * expression must be true: 290 * <pre> 291 * Class.forName(i.getName(), false, cl) == i 292 * </pre> 293 * 294 * <li>All non-public interfaces must be in the same package; 295 * otherwise, it would not be possible for the proxy class to 296 * implement all of the interfaces, regardless of what package it is 297 * defined in. 298 * 299 * <li>For any set of member methods of the specified interfaces 300 * that have the same signature: 301 * <ul> 302 * <li>If the return type of any of the methods is a primitive 303 * type or void, then all of the methods must have that same 304 * return type. 305 * <li>Otherwise, one of the methods must have a return type that 306 * is assignable to all of the return types of the rest of the 307 * methods. 308 * </ul> 309 * 310 * <li>The resulting proxy class must not exceed any limits imposed 311 * on classes by the virtual machine. For example, the VM may limit 312 * the number of interfaces that a class may implement to 65535; in 313 * that case, the size of the {@code interfaces} array must not 314 * exceed 65535. 315 * </ul> 316 * 317 * <p>If any of these restrictions are violated, 318 * {@code Proxy.getProxyClass} will throw an 319 * {@code IllegalArgumentException}. If the {@code interfaces} 320 * array argument or any of its elements are {@code null}, a 321 * {@code NullPointerException} will be thrown. 322 * 323 * <p>Note that the order of the specified proxy interfaces is 324 * significant: two requests for a proxy class with the same combination 325 * of interfaces but in a different order will result in two distinct 326 * proxy classes. 327 * 328 * @param loader the class loader to define the proxy class 329 * @param interfaces the list of interfaces for the proxy class 330 * to implement 331 * @return a proxy class that is defined in the specified class loader 332 * and that implements the specified interfaces 333 * @throws IllegalArgumentException if any of the restrictions on the 334 * parameters that may be passed to {@code getProxyClass} 335 * are violated 336 * @throws SecurityException if a security manager, <em>s</em>, is present 337 * and any of the following conditions is met: 338 * <ul> 339 * <li> the given {@code loader} is {@code null} and 340 * the caller's class loader is not {@code null} and the 341 * invocation of {@link SecurityManager#checkPermission 342 * s.checkPermission} with 343 * {@code RuntimePermission("getClassLoader")} permission 344 * denies access.</li> 345 * <li> the caller's class loader is not the same as or an 346 * ancestor of the class loader for the current class and 347 * invocation of {@link SecurityManager#checkPackageAccess 348 * s.checkPackageAccess()} denies access to any one of the 349 * given proxy interfaces.</li> 350 * </ul> 351 352 * @throws NullPointerException if the {@code interfaces} array 353 * argument or any of its elements are {@code null} 354 */ 355 @CallerSensitive 356 public static Class<?> getProxyClass(ClassLoader loader, 357 Class<?>... interfaces) 358 throws IllegalArgumentException 359 { 360 SecurityManager sm = System.getSecurityManager(); 361 if (sm != null) { 362 checkProxyAccess(Reflection.getCallerClass(), loader, interfaces); 363 } 364 365 return getProxyClass0(loader, interfaces); 366 } 367 368 /* 369 * Check permissions required to create a Proxy class. 370 * 371 * To define a proxy class, it performs the access checks as in 372 * Class.forName (VM will invoke ClassLoader.checkPackageAccess): 373 * 1. "getClassLoader" permission check if loader == null 374 * 2. checkPackageAccess on the interfaces it implements 375 * 376 * To get a constructor and new instance of a proxy class, it performs 377 * the package access check on the interfaces it implements 378 * as in Class.getConstructor. 379 * 380 * If an interface is non-public, the proxy class must be defined by 381 * the defining loader of the interface. If the caller's class loader 382 * is not the same as the defining loader of the interface, the VM 383 * will throw IllegalAccessError when the generated proxy class is 384 * being defined via the defineClass0 method. 385 */ 386 private static void checkProxyAccess(Class<?> caller, 387 ClassLoader loader, 388 Class<?>... interfaces) 389 { 390 SecurityManager sm = System.getSecurityManager(); 391 if (sm != null) { 392 ClassLoader ccl = caller.getClassLoader(); 393 if (VM.isSystemDomainLoader(loader) && !VM.isSystemDomainLoader(ccl)) { 394 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); 395 } 396 ReflectUtil.checkProxyPackageAccess(ccl, interfaces); 397 } 398 } 399 400 /** 401 * Generate a proxy class. Must call the checkProxyAccess method 402 * to perform permission checks before calling this. 403 */ 404 private static Class<?> getProxyClass0(ClassLoader loader, 405 Class<?>... interfaces) { 406 if (interfaces.length > 65535) { 407 throw new IllegalArgumentException("interface limit exceeded"); 408 } 409 410 // If the proxy class defined by the given loader implementing 411 // the given interfaces exists, this will simply return the cached copy; 412 // otherwise, it will create the proxy class via the ProxyClassFactory 413 return proxyClassCache.get(loader, interfaces); 414 } 415 416 /* 417 * a key used for proxy class with 0 implemented interfaces 418 */ 419 private static final Object key0 = new Object(); 420 421 /* 422 * Key1 and Key2 are optimized for the common use of dynamic proxies 423 * that implement 1 or 2 interfaces. 424 */ 425 426 /* 427 * a key used for proxy class with 1 implemented interface 428 */ 429 private static final class Key1 extends WeakReference<Class<?>> { 430 private final int hash; 431 432 Key1(Class<?> intf) { 433 super(intf); 434 this.hash = intf.hashCode(); 435 } 436 437 @Override 438 public int hashCode() { 439 return hash; 440 } 441 442 @Override 443 public boolean equals(Object obj) { 444 Class<?> intf; 445 return this == obj || 446 obj != null && 447 obj.getClass() == Key1.class && 448 (intf = get()) != null && 449 intf == ((Key1) obj).get(); 450 } 451 } 452 453 /* 454 * a key used for proxy class with 2 implemented interfaces 455 */ 456 private static final class Key2 extends WeakReference<Class<?>> { 457 private final int hash; 458 private final WeakReference<Class<?>> ref2; 459 460 Key2(Class<?> intf1, Class<?> intf2) { 461 super(intf1); 462 hash = 31 * intf1.hashCode() + intf2.hashCode(); 463 ref2 = new WeakReference<Class<?>>(intf2); 464 } 465 466 @Override 467 public int hashCode() { 468 return hash; 469 } 470 471 @Override 472 public boolean equals(Object obj) { 473 Class<?> intf1, intf2; 474 return this == obj || 475 obj != null && 476 obj.getClass() == Key2.class && 477 (intf1 = get()) != null && 478 intf1 == ((Key2) obj).get() && 479 (intf2 = ref2.get()) != null && 480 intf2 == ((Key2) obj).ref2.get(); 481 } 482 } 483 484 /* 485 * a key used for proxy class with any number of implemented interfaces 486 * (used here for 3 or more only) 487 */ 488 private static final class KeyX { 489 private final int hash; 490 private final WeakReference<Class<?>>[] refs; 491 492 KeyX(Class<?>[] interfaces) { 493 hash = Arrays.hashCode(interfaces); 494 refs = new WeakReference[interfaces.length]; 495 for (int i = 0; i < interfaces.length; i++) { 496 refs[i] = new WeakReference<>(interfaces[i]); 497 } 498 } 499 500 @Override 501 public int hashCode() { 502 return hash; 503 } 504 505 @Override 506 public boolean equals(Object obj) { 507 return this == obj || 508 obj != null && 509 obj.getClass() == KeyX.class && 510 equals(refs, ((KeyX) obj).refs); 511 } 512 513 private static boolean equals(WeakReference<Class<?>>[] refs1, 514 WeakReference<Class<?>>[] refs2) { 515 if (refs1.length != refs2.length) { 516 return false; 517 } 518 for (int i = 0; i < refs1.length; i++) { 519 Class<?> intf = refs1[i].get(); 520 if (intf == null || intf != refs2[i].get()) { 521 return false; 522 } 523 } 524 return true; 525 } 526 } 527 528 /** 529 * A function that maps an array of interfaces to an optimal key where 530 * Class objects representing interfaces are weakly referenced. 531 */ 532 private static final class KeyFactory 533 implements BiFunction<ClassLoader, Class<?>[], Object> 534 { 535 @Override 536 public Object apply(ClassLoader classLoader, Class<?>[] interfaces) { 537 switch (interfaces.length) { 538 case 1: return new Key1(interfaces[0]); // the most frequent 539 case 2: return new Key2(interfaces[0], interfaces[1]); 540 case 0: return key0; 541 default: return new KeyX(interfaces); 542 } 543 } 544 } 545 546 /** 547 * A factory function that generates, defines and returns the proxy class given 548 * the ClassLoader and array of interfaces. 549 */ 550 private static final class ProxyClassFactory 551 implements BiFunction<ClassLoader, Class<?>[], Class<?>> 552 { 553 // prefix for all proxy class names 554 private static final String proxyClassNamePrefix = "$Proxy"; 555 556 // next number to use for generation of unique proxy class names 557 private static final AtomicLong nextUniqueNumber = new AtomicLong(); 558 559 @Override 560 public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) { 561 562 Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length); 563 for (Class<?> intf : interfaces) { 564 /* 565 * Verify that the class loader resolves the name of this 566 * interface to the same Class object. 567 */ 568 Class<?> interfaceClass = null; 569 try { 570 interfaceClass = Class.forName(intf.getName(), false, loader); 571 } catch (ClassNotFoundException e) { 572 } 573 if (interfaceClass != intf) { 574 throw new IllegalArgumentException( 575 intf + " is not visible from class loader"); 576 } 577 /* 578 * Verify that the Class object actually represents an 579 * interface. 580 */ 581 if (!interfaceClass.isInterface()) { 582 throw new IllegalArgumentException( 583 interfaceClass.getName() + " is not an interface"); 584 } 585 /* 586 * Verify that this interface is not a duplicate. 587 */ 588 if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { 589 throw new IllegalArgumentException( 590 "repeated interface: " + interfaceClass.getName()); 591 } 592 } 593 594 String proxyPkg = null; // package to define proxy class in 595 int accessFlags = Modifier.PUBLIC | Modifier.FINAL; 596 597 /* 598 * Record the package of a non-public proxy interface so that the 599 * proxy class will be defined in the same package. Verify that 600 * all non-public proxy interfaces are in the same package. 601 */ 602 for (Class<?> intf : interfaces) { 603 int flags = intf.getModifiers(); 604 if (!Modifier.isPublic(flags)) { 605 accessFlags = Modifier.FINAL; 606 String name = intf.getName(); 607 int n = name.lastIndexOf('.'); 608 String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); 609 if (proxyPkg == null) { 610 proxyPkg = pkg; 611 } else if (!pkg.equals(proxyPkg)) { 612 throw new IllegalArgumentException( 613 "non-public interfaces from different packages"); 614 } 615 } 616 } 617 618 if (proxyPkg == null) { 619 // if no non-public proxy interfaces, use com.sun.proxy package 620 proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; 621 } 622 623 /* 624 * Choose a name for the proxy class to generate. 625 */ 626 long num = nextUniqueNumber.getAndIncrement(); 627 String proxyName = proxyPkg + proxyClassNamePrefix + num; 628 629 /* 630 * Generate the specified proxy class. 631 */ 632 byte[] proxyClassFile = ProxyGenerator.generateProxyClass( 633 proxyName, interfaces, accessFlags); 634 try { 635 return defineClass0(loader, proxyName, 636 proxyClassFile, 0, proxyClassFile.length); 637 } catch (ClassFormatError e) { 638 /* 639 * A ClassFormatError here means that (barring bugs in the 640 * proxy class generation code) there was some other 641 * invalid aspect of the arguments supplied to the proxy 642 * class creation (such as virtual machine limitations 643 * exceeded). 644 */ 645 throw new IllegalArgumentException(e.toString()); 646 } 647 } 648 } 649 650 /** 651 * Returns an instance of a proxy class for the specified interfaces 652 * that dispatches method invocations to the specified invocation 653 * handler. 654 * 655 * <p>{@code Proxy.newProxyInstance} throws 656 * {@code IllegalArgumentException} for the same reasons that 657 * {@code Proxy.getProxyClass} does. 658 * 659 * @param loader the class loader to define the proxy class 660 * @param interfaces the list of interfaces for the proxy class 661 * to implement 662 * @param h the invocation handler to dispatch method invocations to 663 * @return a proxy instance with the specified invocation handler of a 664 * proxy class that is defined by the specified class loader 665 * and that implements the specified interfaces 666 * @throws IllegalArgumentException if any of the restrictions on the 667 * parameters that may be passed to {@code getProxyClass} 668 * are violated 669 * @throws SecurityException if a security manager, <em>s</em>, is present 670 * and any of the following conditions is met: 671 * <ul> 672 * <li> the given {@code loader} is {@code null} and 673 * the caller's class loader is not {@code null} and the 674 * invocation of {@link SecurityManager#checkPermission 675 * s.checkPermission} with 676 * {@code RuntimePermission("getClassLoader")} permission 677 * denies access;</li> 678 * <li> the caller's class loader is not the same as or an 679 * ancestor of the class loader for the current class and 680 * invocation of {@link SecurityManager#checkPackageAccess 681 * s.checkPackageAccess()} denies access to any one of the 682 * given proxy interfaces.</li> 683 * <li> any of the given proxy interfaces is non-public and the 684 * caller class is not in the same {@linkplain Package runtime package} 685 * as the non-public interface and the invocation of 686 * {@link SecurityManager#checkPermission s.checkPermission} with 687 * {@code ReflectPermission("newProxyInPackage.{package name}")} 688 * permission denies access.</li> 689 * </ul> 690 * @throws NullPointerException if the {@code interfaces} array 691 * argument or any of its elements are {@code null}, or 692 * if the invocation handler, {@code h}, is 693 * {@code null} 694 */ 695 @CallerSensitive 696 public static Object newProxyInstance(ClassLoader loader, 697 Class<?>[] interfaces, 698 InvocationHandler h) 699 throws IllegalArgumentException 700 { 701 if (h == null) { 702 throw new NullPointerException(); 703 } 704 705 final SecurityManager sm = System.getSecurityManager(); 706 if (sm != null) { 707 checkProxyAccess(Reflection.getCallerClass(), loader, interfaces); 708 } 709 710 /* 711 * Look up or generate the designated proxy class. 712 */ 713 Class<?> cl = getProxyClass0(loader, interfaces); 714 715 /* 716 * Invoke its constructor with the designated invocation handler. 717 */ 718 try { 719 if (sm != null) { 720 checkNewProxyPermission(Reflection.getCallerClass(), cl); 721 } 722 723 final Constructor<?> cons = cl.getConstructor(constructorParams); 724 final InvocationHandler ih = h; 725 if (!Modifier.isPublic(cl.getModifiers())) { 726 AccessController.doPrivileged(new PrivilegedAction<Void>() { 727 public Void run() { 728 cons.setAccessible(true); 729 return null; 730 } 731 }); 732 } 733 return cons.newInstance(new Object[]{h}); 734 } catch (IllegalAccessException|InstantiationException e) { 735 throw new InternalError(e.toString(), e); 736 } catch (InvocationTargetException e) { 737 Throwable t = e.getCause(); 738 if (t instanceof RuntimeException) { 739 throw (RuntimeException) t; 740 } else { 741 throw new InternalError(t.toString(), t); 742 } 743 } catch (NoSuchMethodException e) { 744 throw new InternalError(e.toString(), e); 745 } 746 } 747 748 private static void checkNewProxyPermission(Class<?> caller, Class<?> proxyClass) { 749 SecurityManager sm = System.getSecurityManager(); 750 if (sm != null) { 751 String pcn = proxyClass.getName(); 752 if (pcn.startsWith(ReflectUtil.PROXY_PACKAGE + ".")) { 753 // all proxy interfaces are public 754 return; 755 } 756 757 ClassLoader ccl = caller.getClassLoader(); 758 ClassLoader pcl = proxyClass.getClassLoader(); 759 760 // do permission check if the caller is in a different runtime package 761 // of the proxy class 762 int n = pcn.lastIndexOf('.'); 763 String pkg = (n == -1) ? "" : pcn.substring(0, n); 764 765 n = caller.getName().lastIndexOf('.'); 766 String callerPkg = (n == -1) ? "" : caller.getName().substring(0, n); 767 768 if (pcl != ccl || !pkg.equals(callerPkg)) { 769 sm.checkPermission(new ReflectPermission("newProxyInPackage." + pkg)); 770 } 771 } 772 } 773 774 /** 775 * Returns true if and only if the specified class was dynamically 776 * generated to be a proxy class using the {@code getProxyClass} 777 * method or the {@code newProxyInstance} method. 778 * 779 * <p>The reliability of this method is important for the ability 780 * to use it to make security decisions, so its implementation should 781 * not just test if the class in question extends {@code Proxy}. 782 * 783 * @param cl the class to test 784 * @return {@code true} if the class is a proxy class and 785 * {@code false} otherwise 786 * @throws NullPointerException if {@code cl} is {@code null} 787 */ 788 public static boolean isProxyClass(Class<?> cl) { 789 return Proxy.class.isAssignableFrom(cl) && proxyClassCache.containsValue(cl); 790 } 791 792 /** 793 * Returns the invocation handler for the specified proxy instance. 794 * 795 * @param proxy the proxy instance to return the invocation handler for 796 * @return the invocation handler for the proxy instance 797 * @throws IllegalArgumentException if the argument is not a 798 * proxy instance 799 */ 800 public static InvocationHandler getInvocationHandler(Object proxy) 801 throws IllegalArgumentException 802 { 803 /* 804 * Verify that the object is actually a proxy instance. 805 */ 806 if (!isProxyClass(proxy.getClass())) { 807 throw new IllegalArgumentException("not a proxy instance"); 808 } 809 810 Proxy p = (Proxy) proxy; 811 return p.h; 812 } 813 814 private static native Class<?> defineClass0(ClassLoader loader, String name, 815 byte[] b, int off, int len); 816 }