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