001: /*
002: * @(#)Proxy.java 1.16 06/10/10
003: *
004: * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: *
026: */
027:
028: package java.lang.reflect;
029:
030: import java.lang.ref.*;
031: import java.util.*;
032:
033: import sun.misc.ProxyGenerator;
034:
035: /**
036: * <code>Proxy</code> provides static methods for creating dynamic proxy
037: * classes and instances, and it is also the superclass of all
038: * dynamic proxy classes created by those methods.
039: *
040: * <p>To create a proxy for some interface <code>Foo</code>:
041: * <pre>
042: * InvocationHandler handler = new MyInvocationHandler(...);
043: * Class proxyClass = Proxy.getProxyClass(
044: * Foo.class.getClassLoader(), new Class[] { Foo.class });
045: * Foo f = (Foo) proxyClass.
046: * getConstructor(new Class[] { InvocationHandler.class }).
047: * newInstance(new Object[] { handler });
048: * </pre>
049: * or more simply:
050: * <pre>
051: * Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
052: * new Class[] { Foo.class },
053: * handler);
054: * </pre>
055: *
056: * <p>A <i>dynamic proxy class</i> (simply referred to as a <i>proxy
057: * class</i> below) is a class that implements a list of interfaces
058: * specified at runtime when the class is created, with behavior as
059: * described below.
060: *
061: * A <i>proxy interface</i> is such an interface that is implemented
062: * by a proxy class.
063: *
064: * A <i>proxy instance</i> is an instance of a proxy class.
065: *
066: * Each proxy instance has an associated <i>invocation handler</i>
067: * object, which implements the interface {@link InvocationHandler}.
068: * A method invocation on a proxy instance through one of its proxy
069: * interfaces will be dispatched to the {@link InvocationHandler#invoke
070: * invoke} method of the instance's invocation handler, passing the proxy
071: * instance, a <code>java.lang.reflect.Method</code> object identifying
072: * the method that was invoked, and an array of type <code>Object</code>
073: * containing the arguments. The invocation handler processes the
074: * encoded method invocation as appropriate and the result that it
075: * returns will be returned as the result of the method invocation on
076: * the proxy instance.
077: *
078: * <p>A proxy class has the following properties:
079: *
080: * <ul>
081: * <li>Proxy classes are public, final, and not abstract.
082: *
083: * <li>The unqualified name of a proxy class is unspecified. The space
084: * of class names that begin with the string <code>"$Proxy"</code>
085: * should be, however, reserved for proxy classes.
086: *
087: * <li>A proxy class extends <code>java.lang.reflect.Proxy</code>.
088: *
089: * <li>A proxy class implements exactly the interfaces specified at its
090: * creation, in the same order.
091: *
092: * <li>If a proxy class implements a non-public interface, then it will
093: * be defined in the same package as that interface. Otherwise, the
094: * package of a proxy class is also unspecified. Note that package
095: * sealing will not prevent a proxy class from being successfully defined
096: * in a particular package at runtime, and neither will classes already
097: * defined by the same class loader and the same package with particular
098: * signers.
099: *
100: * <li>Since a proxy class implements all of the interfaces specified at
101: * its creation, invoking <code>getInterfaces</code> on its
102: * <code>Class</code> object will return an array containing the same
103: * list of interfaces (in the order specified at its creation), invoking
104: * <code>getMethods</code> on its <code>Class</code> object will return
105: * an array of <code>Method</code> objects that include all of the
106: * methods in those interfaces, and invoking <code>getMethod</code> will
107: * find methods in the proxy interfaces as would be expected.
108: *
109: * <li>The {@link Proxy#isProxyClass Proxy.isProxyClass} method will
110: * return true if it is passed a proxy class-- a class returned by
111: * <code>Proxy.getProxyClass</code> or the class of an object returned by
112: * <code>Proxy.newProxyInstance</code>-- and false otherwise.
113: *
114: * <li>The <code>java.security.ProtectionDomain</code> of a proxy class
115: * is the same as that of system classes loaded by the bootstrap class
116: * loader, such as <code>java.lang.Object</code>, because the code for a
117: * proxy class is generated by trusted system code. This protection
118: * domain will typically be granted
119: * <code>java.security.AllPermission</code>.
120: *
121: * <li>Each proxy class has one public constructor that takes one argument,
122: * an implementation of the interface {@link InvocationHandler}, to set
123: * the invocation handler for a proxy instance. Rather than having to use
124: * the reflection API to access the public constructor, a proxy instance
125: * can be also be created by calling the {@link Proxy#newProxyInstance
126: * Proxy.newInstance} method, which combines the actions of calling
127: * {@link Proxy#getProxyClass Proxy.getProxyClass} with invoking the
128: * constructor with an invocation handler.
129: * </ul>
130: *
131: * <p>A proxy instance has the following properties:
132: *
133: * <ul>
134: * <li>Given a proxy instance <code>proxy</code> and one of the
135: * interfaces implemented by its proxy class <code>Foo</code>, the
136: * following expression will return true:
137: * <pre>
138: * <code>proxy instanceof Foo</code>
139: * </pre>
140: * and the following cast operation will succeed (rather than throwing
141: * a <code>ClassCastException</code>):
142: * <pre>
143: * <code>(Foo) proxy</code>
144: * </pre>
145: *
146: * <li>Each proxy instance has an associated invocation handler, the one
147: * that was passed to its constructor. The static
148: * {@link Proxy#getInvocationHandler Proxy.getInvocationHandler} method
149: * will return the invocation handler associated with the proxy instance
150: * passed as its argument.
151: *
152: * <li>An interface method invocation on a proxy instance will be
153: * encoded and dispatched to the invocation handler's {@link
154: * InvocationHandler#invoke invoke} method as described in the
155: * documentation for that method.
156: *
157: * <li>An invocation of the <code>hashCode</code>,
158: * <code>equals</code>, or <code>toString</code> methods declared in
159: * <code>java.lang.Object</code> on a proxy instance will be encoded and
160: * dispatched to the invocation handler's <code>invoke</code> method in
161: * the same manner as interface method invocations are encoded and
162: * dispatched, as described above. The declaring class of the
163: * <code>Method</code> object passed to <code>invoke</code> will be
164: * <code>java.lang.Object</code>. Other public methods of a proxy
165: * instance inherited from <code>java.lang.Object</code> are not
166: * overridden by a proxy class, so invocations of those methods behave
167: * like they do for instances of <code>java.lang.Object</code>.
168: * </ul>
169: *
170: * <h3>Methods Duplicated in Multiple Proxy Interfaces</h3>
171: *
172: * <p>When two or more interfaces of a proxy class contain a method with
173: * the same name and parameter signature, the order of the proxy class's
174: * interfaces becomes significant. When such a <i>duplicate method</i>
175: * is invoked on a proxy instance, the <code>Method</code> object passed
176: * to the invocation handler will not necessarily be the one whose
177: * declaring class is assignable from the reference type of the interface
178: * that the proxy's method was invoked through. This limitation exists
179: * because the corresponding method implementation in the generated proxy
180: * class cannot determine which interface it was invoked through.
181: * Therefore, when a duplicate method is invoked on a proxy instance,
182: * the <code>Method</code> object for the method in the foremost interface
183: * that contains the method (either directly or inherited through a
184: * superinterface) in the proxy class's list of interfaces is passed to
185: * the invocation handler's <code>invoke</code> method, regardless of the
186: * reference type through which the method invocation occurred.
187: *
188: * <p>If a proxy interface contains a method with the same name and
189: * parameter signature as the <code>hashCode</code>, <code>equals</code>,
190: * or <code>toString</code> methods of <code>java.lang.Object</code>,
191: * when such a method is invoked on a proxy instance, the
192: * <code>Method</code> object passed to the invocation handler will have
193: * <code>java.lang.Object</code> as its declaring class. In other words,
194: * the public, non-final methods of <code>java.lang.Object</code>
195: * logically precede all of the proxy interfaces for the determination of
196: * which <code>Method</code> object to pass to the invocation handler.
197: *
198: * <p>Note also that when a duplicate method is dispatched to an
199: * invocation handler, the <code>invoke</code> method may only throw
200: * checked exception types that are assignable to one of the exception
201: * types in the <code>throws</code> clause of the method in <i>all</i> of
202: * the proxy interfaces that it can be invoked through. If the
203: * <code>invoke</code> method throws a checked exception that is not
204: * assignable to any of the exception types declared by the method in one
205: * of the the proxy interfaces that it can be invoked through, then an
206: * unchecked <code>UndeclaredThrowableException</code> will be thrown by
207: * the invocation on the proxy instance. This restriction means that not
208: * all of the exception types returned by invoking
209: * <code>getExceptionTypes</code> on the <code>Method</code> object
210: * passed to the <code>invoke</code> method can necessarily be thrown
211: * successfully by the <code>invoke</code> method.
212: *
213: * @author Peter Jones
214: * @version 1.8, 00/02/02
215: * @see InvocationHandler
216: * @since JDK1.3
217: */
218: public class Proxy implements java.io.Serializable {
219:
220: /** prefix for all proxy class names */
221: private final static String proxyClassNamePrefix = "$Proxy";
222:
223: /** parameter types of a proxy class constructor */
224: private final static Class[] constructorParams = { InvocationHandler.class };
225:
226: /** maps a class loader to the proxy class cache for that loader */
227: private static Map loaderToCache = new WeakHashMap(3);
228:
229: /** marks that a particular proxy class is currently being generated */
230: private static Object pendingGenerationMarker = new Object();
231:
232: /** next number to use for generation of unique proxy class names */
233: private static long nextUniqueNumber = 0;
234: private static Object nextUniqueNumberLock = new Object();
235:
236: /** set of all generated proxy classes, for isProxyClass implementation */
237: private static Map proxyClasses = Collections
238: .synchronizedMap(new WeakHashMap(3));
239:
240: /**
241: * the invocation handler for this proxy instance.
242: * @serial
243: */
244: protected InvocationHandler h;
245:
246: /**
247: * Prohibits instantiation.
248: */
249: private Proxy() {
250: }
251:
252: /**
253: * Constructs a new <code>Proxy</code> instance from a subclass
254: * (typically, a dynamic proxy class) with the specified value
255: * for its invocation handler.
256: *
257: * @param h the invocation handler for this proxy instance
258: */
259: protected Proxy(InvocationHandler h) {
260: this .h = h;
261: }
262:
263: /**
264: * Returns the <code>java.lang.Class</code> object for a proxy class
265: * given a class loader and an array of interfaces. The proxy class
266: * will be defined by the specified class loader and will implement
267: * all of the supplied interfaces. If a proxy class for the same
268: * permutation of interfaces has already been defined by the class
269: * loader, then the existing proxy class will be returned; otherwise,
270: * a proxy class for those interfaces will be generated dynamically
271: * and defined by the class loader.
272: *
273: * <p>There are several restrictions on the parameters that may be
274: * passed to <code>Proxy.getProxyClass</code>:
275: *
276: * <ul>
277: * <li>All of the <code>Class</code> objects in the
278: * <code>interfaces</code> array must represent interfaces, not
279: * classes or primitive types.
280: *
281: * <li>No two elements in the <code>interfaces</code> array may
282: * refer to identical <code>Class</code> objects.
283: *
284: * <li>All of the interface types must be visible by name through the
285: * specified class loader. In other words, for class loader
286: * <code>cl</code> and every interface <code>i</code>, the following
287: * expression must be true:
288: * <pre>
289: * Class.forName(i.getName(), false, cl) == i
290: * </pre>
291: *
292: * <li>All non-public interfaces must be in the same package;
293: * otherwise, it would not be possible for the proxy class to
294: * implement all of the interfaces, regardless of what package it is
295: * defined in.
296: *
297: * <li>No two interfaces may each have a method with the same name
298: * and parameter signature but different return type.
299: *
300: * <li>The resulting proxy class must not exceed any limits imposed
301: * on classes by the virtual machine. For example, the VM may limit
302: * the number of interfaces that a class may implement to 65535; in
303: * that case, the size of the <code>interfaces</code> array must not
304: * exceed 65535.
305: * </ul>
306: *
307: * <p>If any of these restrictions are violated,
308: * <code>Proxy.getProxyClass</code> will throw an
309: * <code>IllegalArgumentException</code>. If the <code>interfaces</code>
310: * array argument or any of its elements are <code>null</code>, a
311: * <code>NullPointerException</code> will be thrown.
312: *
313: * <p>Note that the order of the specified proxy interfaces is
314: * significant: two requests for a proxy class with the same combination
315: * of interfaces but in a different order will result in two distinct
316: * proxy classes.
317: *
318: * @param loader the class loader to define the proxy class
319: * @param interfaces the list of interfaces for the proxy class
320: * to implement
321: * @return a proxy class that is defined in the specified class loader
322: * and that implements the specified interfaces
323: * @throws IllegalArgumentException if any of the restrictions on the
324: * parameters that may be passed to <code>getProxyClass</code>
325: * are violated
326: * @throws NullPointerException if the <code>interfaces</code> array
327: * argument or any of its elements are <code>null</code>
328: */
329: public static Class getProxyClass(ClassLoader loader,
330: Class[] interfaces) throws IllegalArgumentException {
331: if (interfaces.length > 65535) {
332: throw new IllegalArgumentException(
333: "interface limit exceeded");
334: }
335:
336: Class proxyClass = null;
337:
338: /* buffer to generate string key for proxy class cache */
339: StringBuffer keyBuffer = new StringBuffer();
340:
341: for (int i = 0; i < interfaces.length; i++) {
342: /*
343: * Verify that the class loader resolves the name of this
344: * interface to the same Class object.
345: */
346: Class interfaceClass = null;
347: try {
348: interfaceClass = Class.forName(interfaces[i].getName(),
349: false, loader);
350: } catch (ClassNotFoundException e) {
351: }
352: if (interfaceClass != interfaces[i]) {
353: throw new IllegalArgumentException(interfaces[i]
354: + " is not visible from class loader");
355: }
356:
357: /*
358: * Verify that the Class object actually represents an
359: * interface.
360: */
361: if (!interfaceClass.isInterface()) {
362: throw new IllegalArgumentException(interfaceClass
363: .getName()
364: + " is not an interface");
365: }
366:
367: // continue building string key for proxy class cache
368: keyBuffer.append(interfaces[i].getName()).append(';');
369: }
370:
371: /*
372: * Using a string representation of the proxy interfaces as keys
373: * in the proxy class cache instead of a collection of their Class
374: * objects is sufficiently correct because we require the proxy
375: * interfaces to be resolvable by name through the supplied class
376: * loader, and it has a couple of advantages: matching String
377: * objects is simpler and faster than matching collections of
378: * objects, and using a string representation of a class makes
379: * for an implicit weak reference to the class.
380: */
381: String key = keyBuffer.toString();
382:
383: /*
384: * Find or create the proxy class cache for the class loader.
385: */
386: Map cache;
387: synchronized (loaderToCache) {
388: cache = (Map) loaderToCache.get(loader);
389: if (cache == null) {
390: cache = new HashMap(3);
391: loaderToCache.put(loader, cache);
392: }
393: /*
394: * This mapping will remain valid for the duration of this
395: * method, without further synchronization, because the mapping
396: * will only be removed if the class loader becomes unreachable.
397: */
398: }
399:
400: /*
401: * Look up the list of interfaces in the proxy class cache using
402: * the string key. This lookup will result in one of three possible
403: * kinds of values:
404: * null, if there is currently no proxy class for the list of
405: * interfaces in the class loader,
406: * the pendingGenerationMarker object, if a proxy class for the
407: * list of interfaces is currently being generated,
408: * or a weak reference to a Class object, if a proxy class for
409: * the list of interfaces has already been generated.
410: */
411: synchronized (cache) {
412: /*
413: * Note that we need not worry about reaping the cache for
414: * entries with cleared weak references because if a proxy class
415: * has been garbage collected, its class loader will have been
416: * garbage collected as well, so the entire cache will be reaped
417: * from the loaderToCache map.
418: */
419: do {
420: Object value = cache.get(key);
421: if (value instanceof Reference) {
422: proxyClass = (Class) ((Reference) value).get();
423: }
424: if (proxyClass != null) {
425: // proxy class already generated: return it
426: return proxyClass;
427: } else if (value == pendingGenerationMarker) {
428: // proxy class being generated: wait for it
429: try {
430: cache.wait();
431: } catch (InterruptedException e) {
432: /*
433: * The class generation that we are waiting for should
434: * take a small, bounded time, so we can safely ignore
435: * thread interrupts here.
436: */
437: }
438: continue;
439: } else {
440: /*
441: * No proxy class for this list of interfaces has been
442: * generated or is being generated, so we will go and
443: * generate it now. Mark it as pending generation.
444: */
445: cache.put(key, pendingGenerationMarker);
446: break;
447: }
448: } while (true);
449: }
450:
451: try {
452: String proxyPkg = null; // package to define proxy class in
453:
454: /*
455: * Record the package of a non-public proxy interface so that the
456: * proxy class will be defined in the same package. Verify that
457: * all non-public proxy interfaces are in the same package.
458: */
459: for (int i = 0; i < interfaces.length; i++) {
460: int flags = interfaces[i].getModifiers();
461: if (!Modifier.isPublic(flags)) {
462: String name = interfaces[i].getName();
463: int n = name.lastIndexOf('.');
464: String pkg = ((n == -1) ? "" : name.substring(0,
465: n + 1));
466: if (proxyPkg == null) {
467: proxyPkg = pkg;
468: } else if (!pkg.equals(proxyPkg)) {
469: throw new IllegalArgumentException(
470: "non-public interfaces from different packages");
471: }
472: }
473: }
474:
475: if (proxyPkg == null) { // if no non-public proxy interfaces,
476: proxyPkg = ""; // use the unnamed package
477: }
478:
479: {
480: /*
481: * Choose a name for the proxy class to generate.
482: */
483: long num;
484: synchronized (nextUniqueNumberLock) {
485: num = nextUniqueNumber++;
486: }
487: String proxyName = proxyPkg + proxyClassNamePrefix
488: + num;
489: /*
490: * Verify that the class loader hasn't already
491: * defined a class with the chosen name.
492: */
493:
494: /*
495: * Generate the specified proxy class.
496: */
497: byte[] proxyClassFile = ProxyGenerator
498: .generateProxyClass(proxyName, interfaces);
499: try {
500: proxyClass = defineClass0(loader, proxyName,
501: proxyClassFile, 0, proxyClassFile.length);
502: } catch (ClassFormatError e) {
503: /*
504: * A ClassFormatError here means that (barring bugs in the
505: * proxy class generation code) there was some other
506: * invalid aspect of the arguments supplied to the proxy
507: * class creation (such as virtual machine limitations
508: * exceeded).
509: */
510: throw new IllegalArgumentException(e.toString());
511: }
512: }
513: // add to set of all generated proxy classes, for isProxyClass
514: proxyClasses.put(proxyClass, null);
515:
516: } finally {
517: /*
518: * We must clean up the "pending generation" state of the proxy
519: * class cache entry somehow. If a proxy class was successfully
520: * generated, store it in the cache (with a weak reference);
521: * otherwise, remove the reserved entry. In all cases, notify
522: * all waiters on reserved entries in this cache.
523: */
524: synchronized (cache) {
525: if (proxyClass != null) {
526: cache.put(key, new WeakReference(proxyClass));
527: } else {
528: cache.remove(key);
529: }
530: cache.notifyAll();
531: }
532: }
533: return proxyClass;
534: }
535:
536: /**
537: * Returns an instance of a proxy class for the specified interfaces
538: * that dispatches method invocations to the specified invocation
539: * handler. This method is equivalent to:
540: * <pre>
541: * Proxy.getProxyClass(loader, interfaces).
542: * getConstructor(new Class[] { InvocationHandler.class }).
543: * newInstance(new Object[] { handler });
544: * </pre>
545: *
546: * <p><code>Proxy.newProxyInstance</code> throws
547: * <code>IllegalArgumentException</code> for the same reasons that
548: * <code>Proxy.getProxyClass</code> does.
549: *
550: * @param loader the class loader to define the proxy class
551: * @param interfaces the list of interfaces for the proxy class
552: * to implement
553: * @param h the invocation handler to dispatch method invocations to
554: * @return a proxy instance with the specified invocation handler of a
555: * proxy class that is defined by the specified class loader
556: * and that implements the specified interfaces
557: * @throws IllegalArgumentException if any of the restrictions on the
558: * parameters that may be passed to <code>getProxyClass</code>
559: * are violated
560: * @throws NullPointerException if the <code>interfaces</code> array
561: * argument or any of its elements are <code>null</code>, or
562: * if the invocation handler, <code>h</code>, is
563: * <code>null</code>
564: */
565: public static Object newProxyInstance(ClassLoader loader,
566: Class[] interfaces, InvocationHandler h)
567: throws IllegalArgumentException {
568: if (h == null) {
569: throw new NullPointerException();
570: }
571:
572: /*
573: * Look up or generate the designated proxy class.
574: */
575: Class cl = getProxyClass(loader, interfaces);
576:
577: /*
578: * Invoke its constructor with the designated invocation handler.
579: */
580: try {
581: Constructor cons = cl.getConstructor(constructorParams);
582: return (Object) cons.newInstance(new Object[] { h });
583: } catch (NoSuchMethodException e) {
584: throw new InternalError(e.toString());
585: } catch (IllegalAccessException e) {
586: throw new InternalError(e.toString());
587: } catch (InstantiationException e) {
588: throw new InternalError(e.toString());
589: } catch (InvocationTargetException e) {
590: throw new InternalError(e.toString());
591: }
592: }
593:
594: /**
595: * Returns true if and only if the specified class was dynamically
596: * generated to be a proxy class using the <code>getProxyClass</code>
597: * method or the <code>newProxyInstance</code> method.
598: *
599: * <p>The reliability of this method is important for the ability
600: * to use it to make security decisions, so its implementation should
601: * not just test if the class in question extends <code>Proxy</code>.
602: *
603: * @param cl the class to test
604: * @return <code>true</code> if the class is a proxy class and
605: * <code>false</code> otherwise
606: * @throws NullPointerException if <code>cl</code> is <code>null</code>
607: */
608: public static boolean isProxyClass(Class cl) {
609: if (cl == null) {
610: throw new NullPointerException();
611: }
612:
613: return proxyClasses.containsKey(cl);
614: }
615:
616: /**
617: * Returns the invocation handler for the specified proxy instance.
618: *
619: * @param proxy the proxy instance to return the invocation handler for
620: * @return the invocation handler for the proxy instance
621: * @throws IllegalArgumentException if the argument is not a
622: * proxy instance
623: */
624: public static InvocationHandler getInvocationHandler(Object proxy)
625: throws IllegalArgumentException {
626: /*
627: * Verify that the object is actually a proxy instance.
628: */
629: if (!isProxyClass(proxy.getClass())) {
630: throw new IllegalArgumentException("not a proxy instance");
631: }
632:
633: Proxy p = (Proxy) proxy;
634: return p.h;
635: }
636:
637: private static native Class defineClass0(ClassLoader loader,
638: String name, byte[] b, int off, int len);
639: }
|