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