1. /*
  2. * @(#)Proxy.java 1.20 04/04/20
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.lang.reflect;
  8. import java.lang.ref.Reference;
  9. import java.lang.ref.WeakReference;
  10. import java.util.Arrays;
  11. import java.util.Collections;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. import java.util.WeakHashMap;
  15. import sun.misc.ProxyGenerator;
  16. /**
  17. * <code>Proxy</code> provides static methods for creating dynamic proxy
  18. * classes and instances, and it is also the superclass of all
  19. * dynamic proxy classes created by those methods.
  20. *
  21. * <p>To create a proxy for some interface <code>Foo</code>:
  22. * <pre>
  23. * InvocationHandler handler = new MyInvocationHandler(...);
  24. * Class proxyClass = Proxy.getProxyClass(
  25. * Foo.class.getClassLoader(), new Class[] { Foo.class });
  26. * Foo f = (Foo) proxyClass.
  27. * getConstructor(new Class[] { InvocationHandler.class }).
  28. * newInstance(new Object[] { handler });
  29. * </pre>
  30. * or more simply:
  31. * <pre>
  32. * Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
  33. * new Class[] { Foo.class },
  34. * handler);
  35. * </pre>
  36. *
  37. * <p>A <i>dynamic proxy class</i> (simply referred to as a <i>proxy
  38. * class</i> below) is a class that implements a list of interfaces
  39. * specified at runtime when the class is created, with behavior as
  40. * described below.
  41. *
  42. * A <i>proxy interface</i> is such an interface that is implemented
  43. * by a proxy class.
  44. *
  45. * A <i>proxy instance</i> is an instance of a proxy class.
  46. *
  47. * Each proxy instance has an associated <i>invocation handler</i>
  48. * object, which implements the interface {@link InvocationHandler}.
  49. * A method invocation on a proxy instance through one of its proxy
  50. * interfaces will be dispatched to the {@link InvocationHandler#invoke
  51. * invoke} method of the instance's invocation handler, passing the proxy
  52. * instance, a <code>java.lang.reflect.Method</code> object identifying
  53. * the method that was invoked, and an array of type <code>Object</code>
  54. * containing the arguments. The invocation handler processes the
  55. * encoded method invocation as appropriate and the result that it
  56. * returns will be returned as the result of the method invocation on
  57. * the proxy instance.
  58. *
  59. * <p>A proxy class has the following properties:
  60. *
  61. * <ul>
  62. * <li>Proxy classes are public, final, and not abstract.
  63. *
  64. * <li>The unqualified name of a proxy class is unspecified. The space
  65. * of class names that begin with the string <code>"$Proxy"</code>
  66. * should be, however, reserved for proxy classes.
  67. *
  68. * <li>A proxy class extends <code>java.lang.reflect.Proxy</code>.
  69. *
  70. * <li>A proxy class implements exactly the interfaces specified at its
  71. * creation, in the same order.
  72. *
  73. * <li>If a proxy class implements a non-public interface, then it will
  74. * be defined in the same package as that interface. Otherwise, the
  75. * package of a proxy class is also unspecified. Note that package
  76. * sealing will not prevent a proxy class from being successfully defined
  77. * in a particular package at runtime, and neither will classes already
  78. * defined by the same class loader and the same package with particular
  79. * signers.
  80. *
  81. * <li>Since a proxy class implements all of the interfaces specified at
  82. * its creation, invoking <code>getInterfaces</code> on its
  83. * <code>Class</code> object will return an array containing the same
  84. * list of interfaces (in the order specified at its creation), invoking
  85. * <code>getMethods</code> on its <code>Class</code> object will return
  86. * an array of <code>Method</code> objects that include all of the
  87. * methods in those interfaces, and invoking <code>getMethod</code> will
  88. * find methods in the proxy interfaces as would be expected.
  89. *
  90. * <li>The {@link Proxy#isProxyClass Proxy.isProxyClass} method will
  91. * return true if it is passed a proxy class-- a class returned by
  92. * <code>Proxy.getProxyClass</code> or the class of an object returned by
  93. * <code>Proxy.newProxyInstance</code>-- and false otherwise.
  94. *
  95. * <li>The <code>java.security.ProtectionDomain</code> of a proxy class
  96. * is the same as that of system classes loaded by the bootstrap class
  97. * loader, such as <code>java.lang.Object</code>, because the code for a
  98. * proxy class is generated by trusted system code. This protection
  99. * domain will typically be granted
  100. * <code>java.security.AllPermission</code>.
  101. *
  102. * <li>Each proxy class has one public constructor that takes one argument,
  103. * an implementation of the interface {@link InvocationHandler}, to set
  104. * the invocation handler for a proxy instance. Rather than having to use
  105. * the reflection API to access the public constructor, a proxy instance
  106. * can be also be created by calling the {@link Proxy#newProxyInstance
  107. * Proxy.newInstance} method, which combines the actions of calling
  108. * {@link Proxy#getProxyClass Proxy.getProxyClass} with invoking the
  109. * constructor with an invocation handler.
  110. * </ul>
  111. *
  112. * <p>A proxy instance has the following properties:
  113. *
  114. * <ul>
  115. * <li>Given a proxy instance <code>proxy</code> and one of the
  116. * interfaces implemented by its proxy class <code>Foo</code>, the
  117. * following expression will return true:
  118. * <pre>
  119. * <code>proxy instanceof Foo</code>
  120. * </pre>
  121. * and the following cast operation will succeed (rather than throwing
  122. * a <code>ClassCastException</code>):
  123. * <pre>
  124. * <code>(Foo) proxy</code>
  125. * </pre>
  126. *
  127. * <li>Each proxy instance has an associated invocation handler, the one
  128. * that was passed to its constructor. The static
  129. * {@link Proxy#getInvocationHandler Proxy.getInvocationHandler} method
  130. * will return the invocation handler associated with the proxy instance
  131. * passed as its argument.
  132. *
  133. * <li>An interface method invocation on a proxy instance will be
  134. * encoded and dispatched to the invocation handler's {@link
  135. * InvocationHandler#invoke invoke} method as described in the
  136. * documentation for that method.
  137. *
  138. * <li>An invocation of the <code>hashCode</code>,
  139. * <code>equals</code>, or <code>toString</code> methods declared in
  140. * <code>java.lang.Object</code> on a proxy instance will be encoded and
  141. * dispatched to the invocation handler's <code>invoke</code> method in
  142. * the same manner as interface method invocations are encoded and
  143. * dispatched, as described above. The declaring class of the
  144. * <code>Method</code> object passed to <code>invoke</code> will be
  145. * <code>java.lang.Object</code>. Other public methods of a proxy
  146. * instance inherited from <code>java.lang.Object</code> are not
  147. * overridden by a proxy class, so invocations of those methods behave
  148. * like they do for instances of <code>java.lang.Object</code>.
  149. * </ul>
  150. *
  151. * <h3>Methods Duplicated in Multiple Proxy Interfaces</h3>
  152. *
  153. * <p>When two or more interfaces of a proxy class contain a method with
  154. * the same name and parameter signature, the order of the proxy class's
  155. * interfaces becomes significant. When such a <i>duplicate method</i>
  156. * is invoked on a proxy instance, the <code>Method</code> object passed
  157. * to the invocation handler will not necessarily be the one whose
  158. * declaring class is assignable from the reference type of the interface
  159. * that the proxy's method was invoked through. This limitation exists
  160. * because the corresponding method implementation in the generated proxy
  161. * class cannot determine which interface it was invoked through.
  162. * Therefore, when a duplicate method is invoked on a proxy instance,
  163. * the <code>Method</code> object for the method in the foremost interface
  164. * that contains the method (either directly or inherited through a
  165. * superinterface) in the proxy class's list of interfaces is passed to
  166. * the invocation handler's <code>invoke</code> method, regardless of the
  167. * reference type through which the method invocation occurred.
  168. *
  169. * <p>If a proxy interface contains a method with the same name and
  170. * parameter signature as the <code>hashCode</code>, <code>equals</code>,
  171. * or <code>toString</code> methods of <code>java.lang.Object</code>,
  172. * when such a method is invoked on a proxy instance, the
  173. * <code>Method</code> object passed to the invocation handler will have
  174. * <code>java.lang.Object</code> as its declaring class. In other words,
  175. * the public, non-final methods of <code>java.lang.Object</code>
  176. * logically precede all of the proxy interfaces for the determination of
  177. * which <code>Method</code> object to pass to the invocation handler.
  178. *
  179. * <p>Note also that when a duplicate method is dispatched to an
  180. * invocation handler, the <code>invoke</code> method may only throw
  181. * checked exception types that are assignable to one of the exception
  182. * types in the <code>throws</code> clause of the method in <i>all</i> of
  183. * the proxy interfaces that it can be invoked through. If the
  184. * <code>invoke</code> method throws a checked exception that is not
  185. * assignable to any of the exception types declared by the method in one
  186. * of the proxy interfaces that it can be invoked through, then an
  187. * unchecked <code>UndeclaredThrowableException</code> will be thrown by
  188. * the invocation on the proxy instance. This restriction means that not
  189. * all of the exception types returned by invoking
  190. * <code>getExceptionTypes</code> on the <code>Method</code> object
  191. * passed to the <code>invoke</code> method can necessarily be thrown
  192. * successfully by the <code>invoke</code> method.
  193. *
  194. * @author Peter Jones
  195. * @version 1.20, 04/04/20
  196. * @see InvocationHandler
  197. * @since 1.3
  198. */
  199. public class Proxy implements java.io.Serializable {
  200. private static final long serialVersionUID = -2222568056686623797L;
  201. /** prefix for all proxy class names */
  202. private final static String proxyClassNamePrefix = "$Proxy";
  203. /** parameter types of a proxy class constructor */
  204. private final static Class[] constructorParams =
  205. { InvocationHandler.class };
  206. /** maps a class loader to the proxy class cache for that loader */
  207. private static Map loaderToCache = new WeakHashMap();
  208. /** marks that a particular proxy class is currently being generated */
  209. private static Object pendingGenerationMarker = new Object();
  210. /** next number to use for generation of unique proxy class names */
  211. private static long nextUniqueNumber = 0;
  212. private static Object nextUniqueNumberLock = new Object();
  213. /** set of all generated proxy classes, for isProxyClass implementation */
  214. private static Map proxyClasses =
  215. Collections.synchronizedMap(new WeakHashMap());
  216. /**
  217. * the invocation handler for this proxy instance.
  218. * @serial
  219. */
  220. protected InvocationHandler h;
  221. /**
  222. * Prohibits instantiation.
  223. */
  224. private Proxy() {
  225. }
  226. /**
  227. * Constructs a new <code>Proxy</code> instance from a subclass
  228. * (typically, a dynamic proxy class) with the specified value
  229. * for its invocation handler.
  230. *
  231. * @param h the invocation handler for this proxy instance
  232. */
  233. protected Proxy(InvocationHandler h) {
  234. this.h = h;
  235. }
  236. /**
  237. * Returns the <code>java.lang.Class</code> object for a proxy class
  238. * given a class loader and an array of interfaces. The proxy class
  239. * will be defined by the specified class loader and will implement
  240. * all of the supplied interfaces. If a proxy class for the same
  241. * permutation of interfaces has already been defined by the class
  242. * loader, then the existing proxy class will be returned; otherwise,
  243. * a proxy class for those interfaces will be generated dynamically
  244. * and defined by the class loader.
  245. *
  246. * <p>There are several restrictions on the parameters that may be
  247. * passed to <code>Proxy.getProxyClass</code>:
  248. *
  249. * <ul>
  250. * <li>All of the <code>Class</code> objects in the
  251. * <code>interfaces</code> array must represent interfaces, not
  252. * classes or primitive types.
  253. *
  254. * <li>No two elements in the <code>interfaces</code> array may
  255. * refer to identical <code>Class</code> objects.
  256. *
  257. * <li>All of the interface types must be visible by name through the
  258. * specified class loader. In other words, for class loader
  259. * <code>cl</code> and every interface <code>i</code>, the following
  260. * expression must be true:
  261. * <pre>
  262. * Class.forName(i.getName(), false, cl) == i
  263. * </pre>
  264. *
  265. * <li>All non-public interfaces must be in the same package;
  266. * otherwise, it would not be possible for the proxy class to
  267. * implement all of the interfaces, regardless of what package it is
  268. * defined in.
  269. *
  270. * <li>For any set of member methods of the specified interfaces
  271. * that have the same signature:
  272. * <ul>
  273. * <li>If the return type of any of the methods is a primitive
  274. * type or void, then all of the methods must have that same
  275. * return type.
  276. * <li>Otherwise, one of the methods must have a return type that
  277. * is assignable to all of the return types of the rest of the
  278. * methods.
  279. * </ul>
  280. *
  281. * <li>The resulting proxy class must not exceed any limits imposed
  282. * on classes by the virtual machine. For example, the VM may limit
  283. * the number of interfaces that a class may implement to 65535; in
  284. * that case, the size of the <code>interfaces</code> array must not
  285. * exceed 65535.
  286. * </ul>
  287. *
  288. * <p>If any of these restrictions are violated,
  289. * <code>Proxy.getProxyClass</code> will throw an
  290. * <code>IllegalArgumentException</code>. If the <code>interfaces</code>
  291. * array argument or any of its elements are <code>null</code>, a
  292. * <code>NullPointerException</code> will be thrown.
  293. *
  294. * <p>Note that the order of the specified proxy interfaces is
  295. * significant: two requests for a proxy class with the same combination
  296. * of interfaces but in a different order will result in two distinct
  297. * proxy classes.
  298. *
  299. * @param loader the class loader to define the proxy class
  300. * @param interfaces the list of interfaces for the proxy class
  301. * to implement
  302. * @return a proxy class that is defined in the specified class loader
  303. * and that implements the specified interfaces
  304. * @throws IllegalArgumentException if any of the restrictions on the
  305. * parameters that may be passed to <code>getProxyClass</code>
  306. * are violated
  307. * @throws NullPointerException if the <code>interfaces</code> array
  308. * argument or any of its elements are <code>null</code>
  309. */
  310. public static Class<?> getProxyClass(ClassLoader loader,
  311. Class<?>... interfaces)
  312. throws IllegalArgumentException
  313. {
  314. Class proxyClass = null;
  315. /* collect interface names to use as key for proxy class cache */
  316. String[] interfaceNames = new String[interfaces.length];
  317. for (int i = 0; i < interfaces.length; i++) {
  318. /*
  319. * Verify that the class loader resolves the name of this
  320. * interface to the same Class object.
  321. */
  322. String interfaceName = interfaces[i].getName();
  323. Class interfaceClass = null;
  324. try {
  325. interfaceClass = Class.forName(interfaceName, false, loader);
  326. } catch (ClassNotFoundException e) {
  327. }
  328. if (interfaceClass != interfaces[i]) {
  329. throw new IllegalArgumentException(
  330. interfaces[i] + " is not visible from class loader");
  331. }
  332. /*
  333. * Verify that the Class object actually represents an
  334. * interface.
  335. */
  336. if (!interfaceClass.isInterface()) {
  337. throw new IllegalArgumentException(
  338. interfaceClass.getName() + " is not an interface");
  339. }
  340. interfaceNames[i] = interfaceName;
  341. }
  342. /*
  343. * Using string representations of the proxy interfaces as
  344. * keys in the proxy class cache (instead of their Class
  345. * objects) is sufficient because we require the proxy
  346. * interfaces to be resolvable by name through the supplied
  347. * class loader, and it has the advantage that using a string
  348. * representation of a class makes for an implicit weak
  349. * reference to the class.
  350. */
  351. Object key = Arrays.asList(interfaceNames);
  352. /*
  353. * Find or create the proxy class cache for the class loader.
  354. */
  355. Map cache;
  356. synchronized (loaderToCache) {
  357. cache = (Map) loaderToCache.get(loader);
  358. if (cache == null) {
  359. cache = new HashMap();
  360. loaderToCache.put(loader, cache);
  361. }
  362. /*
  363. * This mapping will remain valid for the duration of this
  364. * method, without further synchronization, because the mapping
  365. * will only be removed if the class loader becomes unreachable.
  366. */
  367. }
  368. /*
  369. * Look up the list of interfaces in the proxy class cache using
  370. * the key. This lookup will result in one of three possible
  371. * kinds of values:
  372. * null, if there is currently no proxy class for the list of
  373. * interfaces in the class loader,
  374. * the pendingGenerationMarker object, if a proxy class for the
  375. * list of interfaces is currently being generated,
  376. * or a weak reference to a Class object, if a proxy class for
  377. * the list of interfaces has already been generated.
  378. */
  379. synchronized (cache) {
  380. /*
  381. * Note that we need not worry about reaping the cache for
  382. * entries with cleared weak references because if a proxy class
  383. * has been garbage collected, its class loader will have been
  384. * garbage collected as well, so the entire cache will be reaped
  385. * from the loaderToCache map.
  386. */
  387. do {
  388. Object value = cache.get(key);
  389. if (value instanceof Reference) {
  390. proxyClass = (Class) ((Reference) value).get();
  391. }
  392. if (proxyClass != null) {
  393. // proxy class already generated: return it
  394. return proxyClass;
  395. } else if (value == pendingGenerationMarker) {
  396. // proxy class being generated: wait for it
  397. try {
  398. cache.wait();
  399. } catch (InterruptedException e) {
  400. /*
  401. * The class generation that we are waiting for should
  402. * take a small, bounded time, so we can safely ignore
  403. * thread interrupts here.
  404. */
  405. }
  406. continue;
  407. } else {
  408. /*
  409. * No proxy class for this list of interfaces has been
  410. * generated or is being generated, so we will go and
  411. * generate it now. Mark it as pending generation.
  412. */
  413. cache.put(key, pendingGenerationMarker);
  414. break;
  415. }
  416. } while (true);
  417. }
  418. try {
  419. String proxyPkg = null; // package to define proxy class in
  420. /*
  421. * Record the package of a non-public proxy interface so that the
  422. * proxy class will be defined in the same package. Verify that
  423. * all non-public proxy interfaces are in the same package.
  424. */
  425. for (int i = 0; i < interfaces.length; i++) {
  426. int flags = interfaces[i].getModifiers();
  427. if (!Modifier.isPublic(flags)) {
  428. String name = interfaces[i].getName();
  429. int n = name.lastIndexOf('.');
  430. String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
  431. if (proxyPkg == null) {
  432. proxyPkg = pkg;
  433. } else if (!pkg.equals(proxyPkg)) {
  434. throw new IllegalArgumentException(
  435. "non-public interfaces from different packages");
  436. }
  437. }
  438. }
  439. if (proxyPkg == null) { // if no non-public proxy interfaces,
  440. proxyPkg = ""; // use the unnamed package
  441. }
  442. {
  443. /*
  444. * Choose a name for the proxy class to generate.
  445. */
  446. long num;
  447. synchronized (nextUniqueNumberLock) {
  448. num = nextUniqueNumber++;
  449. }
  450. String proxyName = proxyPkg + proxyClassNamePrefix + num;
  451. /*
  452. * Verify that the class loader hasn't already
  453. * defined a class with the chosen name.
  454. */
  455. /*
  456. * Generate the specified proxy class.
  457. */
  458. byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
  459. proxyName, interfaces);
  460. try {
  461. proxyClass = defineClass0(loader, proxyName,
  462. proxyClassFile, 0, proxyClassFile.length);
  463. } catch (ClassFormatError e) {
  464. /*
  465. * A ClassFormatError here means that (barring bugs in the
  466. * proxy class generation code) there was some other
  467. * invalid aspect of the arguments supplied to the proxy
  468. * class creation (such as virtual machine limitations
  469. * exceeded).
  470. */
  471. throw new IllegalArgumentException(e.toString());
  472. }
  473. }
  474. // add to set of all generated proxy classes, for isProxyClass
  475. proxyClasses.put(proxyClass, null);
  476. } finally {
  477. /*
  478. * We must clean up the "pending generation" state of the proxy
  479. * class cache entry somehow. If a proxy class was successfully
  480. * generated, store it in the cache (with a weak reference);
  481. * otherwise, remove the reserved entry. In all cases, notify
  482. * all waiters on reserved entries in this cache.
  483. */
  484. synchronized (cache) {
  485. if (proxyClass != null) {
  486. cache.put(key, new WeakReference(proxyClass));
  487. } else {
  488. cache.remove(key);
  489. }
  490. cache.notifyAll();
  491. }
  492. }
  493. return proxyClass;
  494. }
  495. /**
  496. * Returns an instance of a proxy class for the specified interfaces
  497. * that dispatches method invocations to the specified invocation
  498. * handler. This method is equivalent to:
  499. * <pre>
  500. * Proxy.getProxyClass(loader, interfaces).
  501. * getConstructor(new Class[] { InvocationHandler.class }).
  502. * newInstance(new Object[] { handler });
  503. * </pre>
  504. *
  505. * <p><code>Proxy.newProxyInstance</code> throws
  506. * <code>IllegalArgumentException</code> for the same reasons that
  507. * <code>Proxy.getProxyClass</code> does.
  508. *
  509. * @param loader the class loader to define the proxy class
  510. * @param interfaces the list of interfaces for the proxy class
  511. * to implement
  512. * @param h the invocation handler to dispatch method invocations to
  513. * @return a proxy instance with the specified invocation handler of a
  514. * proxy class that is defined by the specified class loader
  515. * and that implements the specified interfaces
  516. * @throws IllegalArgumentException if any of the restrictions on the
  517. * parameters that may be passed to <code>getProxyClass</code>
  518. * are violated
  519. * @throws NullPointerException if the <code>interfaces</code> array
  520. * argument or any of its elements are <code>null</code>, or
  521. * if the invocation handler, <code>h</code>, is
  522. * <code>null</code>
  523. */
  524. public static Object newProxyInstance(ClassLoader loader,
  525. Class<?>[] interfaces,
  526. InvocationHandler h)
  527. throws IllegalArgumentException
  528. {
  529. if (h == null) {
  530. throw new NullPointerException();
  531. }
  532. /*
  533. * Look up or generate the designated proxy class.
  534. */
  535. Class cl = getProxyClass(loader, interfaces);
  536. /*
  537. * Invoke its constructor with the designated invocation handler.
  538. */
  539. try {
  540. Constructor cons = cl.getConstructor(constructorParams);
  541. return (Object) cons.newInstance(new Object[] { h });
  542. } catch (NoSuchMethodException e) {
  543. throw new InternalError(e.toString());
  544. } catch (IllegalAccessException e) {
  545. throw new InternalError(e.toString());
  546. } catch (InstantiationException e) {
  547. throw new InternalError(e.toString());
  548. } catch (InvocationTargetException e) {
  549. throw new InternalError(e.toString());
  550. }
  551. }
  552. /**
  553. * Returns true if and only if the specified class was dynamically
  554. * generated to be a proxy class using the <code>getProxyClass</code>
  555. * method or the <code>newProxyInstance</code> method.
  556. *
  557. * <p>The reliability of this method is important for the ability
  558. * to use it to make security decisions, so its implementation should
  559. * not just test if the class in question extends <code>Proxy</code>.
  560. *
  561. * @param cl the class to test
  562. * @return <code>true</code> if the class is a proxy class and
  563. * <code>false</code> otherwise
  564. * @throws NullPointerException if <code>cl</code> is <code>null</code>
  565. */
  566. public static boolean isProxyClass(Class<?> cl) {
  567. if (cl == null) {
  568. throw new NullPointerException();
  569. }
  570. return proxyClasses.containsKey(cl);
  571. }
  572. /**
  573. * Returns the invocation handler for the specified proxy instance.
  574. *
  575. * @param proxy the proxy instance to return the invocation handler for
  576. * @return the invocation handler for the proxy instance
  577. * @throws IllegalArgumentException if the argument is not a
  578. * proxy instance
  579. */
  580. public static InvocationHandler getInvocationHandler(Object proxy)
  581. throws IllegalArgumentException
  582. {
  583. /*
  584. * Verify that the object is actually a proxy instance.
  585. */
  586. if (!isProxyClass(proxy.getClass())) {
  587. throw new IllegalArgumentException("not a proxy instance");
  588. }
  589. Proxy p = (Proxy) proxy;
  590. return p.h;
  591. }
  592. private static native Class defineClass0(ClassLoader loader, String name,
  593. byte[] b, int off, int len);
  594. }