jaroslav@601: /* jaroslav@601: * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved. jaroslav@601: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@601: * jaroslav@601: * This code is free software; you can redistribute it and/or modify it jaroslav@601: * under the terms of the GNU General Public License version 2 only, as jaroslav@601: * published by the Free Software Foundation. Oracle designates this jaroslav@601: * particular file as subject to the "Classpath" exception as provided jaroslav@601: * by Oracle in the LICENSE file that accompanied this code. jaroslav@601: * jaroslav@601: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@601: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@601: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@601: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@601: * accompanied this code). jaroslav@601: * jaroslav@601: * You should have received a copy of the GNU General Public License version jaroslav@601: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@601: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@601: * jaroslav@601: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@601: * or visit www.oracle.com if you need additional information or have any jaroslav@601: * questions. jaroslav@601: */ jaroslav@601: jaroslav@601: package java.lang.reflect; jaroslav@601: jaroslav@601: import java.lang.ref.Reference; jaroslav@601: import java.lang.ref.WeakReference; jaroslav@601: import java.util.Arrays; jaroslav@601: import java.util.Collections; jaroslav@601: import java.util.HashMap; jaroslav@601: import java.util.HashSet; jaroslav@601: import java.util.Map; jaroslav@601: import java.util.Set; jaroslav@601: import java.util.List; jaroslav@601: import java.util.WeakHashMap; jaroslav@601: import sun.misc.ProxyGenerator; jaroslav@601: jaroslav@601: /** jaroslav@601: * {@code Proxy} provides static methods for creating dynamic proxy jaroslav@601: * classes and instances, and it is also the superclass of all jaroslav@601: * dynamic proxy classes created by those methods. jaroslav@601: * jaroslav@601: *
To create a proxy for some interface {@code Foo}: jaroslav@601: *
jaroslav@601: * InvocationHandler handler = new MyInvocationHandler(...); jaroslav@601: * Class proxyClass = Proxy.getProxyClass( jaroslav@601: * Foo.class.getClassLoader(), new Class[] { Foo.class }); jaroslav@601: * Foo f = (Foo) proxyClass. jaroslav@601: * getConstructor(new Class[] { InvocationHandler.class }). jaroslav@601: * newInstance(new Object[] { handler }); jaroslav@601: *jaroslav@601: * or more simply: jaroslav@601: *
jaroslav@601: * Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), jaroslav@601: * new Class[] { Foo.class }, jaroslav@601: * handler); jaroslav@601: *jaroslav@601: * jaroslav@601: *
A dynamic proxy class (simply referred to as a proxy jaroslav@601: * class below) is a class that implements a list of interfaces jaroslav@601: * specified at runtime when the class is created, with behavior as jaroslav@601: * described below. jaroslav@601: * jaroslav@601: * A proxy interface is such an interface that is implemented jaroslav@601: * by a proxy class. jaroslav@601: * jaroslav@601: * A proxy instance is an instance of a proxy class. jaroslav@601: * jaroslav@601: * Each proxy instance has an associated invocation handler jaroslav@601: * object, which implements the interface {@link InvocationHandler}. jaroslav@601: * A method invocation on a proxy instance through one of its proxy jaroslav@601: * interfaces will be dispatched to the {@link InvocationHandler#invoke jaroslav@601: * invoke} method of the instance's invocation handler, passing the proxy jaroslav@601: * instance, a {@code java.lang.reflect.Method} object identifying jaroslav@601: * the method that was invoked, and an array of type {@code Object} jaroslav@601: * containing the arguments. The invocation handler processes the jaroslav@601: * encoded method invocation as appropriate and the result that it jaroslav@601: * returns will be returned as the result of the method invocation on jaroslav@601: * the proxy instance. jaroslav@601: * jaroslav@601: *
A proxy class has the following properties: jaroslav@601: * jaroslav@601: *
A proxy instance has the following properties: jaroslav@601: * jaroslav@601: *
jaroslav@601: * {@code proxy instanceof Foo} jaroslav@601: *jaroslav@601: * and the following cast operation will succeed (rather than throwing jaroslav@601: * a {@code ClassCastException}): jaroslav@601: *
jaroslav@601: * {@code (Foo) proxy} jaroslav@601: *jaroslav@601: * jaroslav@601: *
When two or more interfaces of a proxy class contain a method with jaroslav@601: * the same name and parameter signature, the order of the proxy class's jaroslav@601: * interfaces becomes significant. When such a duplicate method jaroslav@601: * is invoked on a proxy instance, the {@code Method} object passed jaroslav@601: * to the invocation handler will not necessarily be the one whose jaroslav@601: * declaring class is assignable from the reference type of the interface jaroslav@601: * that the proxy's method was invoked through. This limitation exists jaroslav@601: * because the corresponding method implementation in the generated proxy jaroslav@601: * class cannot determine which interface it was invoked through. jaroslav@601: * Therefore, when a duplicate method is invoked on a proxy instance, jaroslav@601: * the {@code Method} object for the method in the foremost interface jaroslav@601: * that contains the method (either directly or inherited through a jaroslav@601: * superinterface) in the proxy class's list of interfaces is passed to jaroslav@601: * the invocation handler's {@code invoke} method, regardless of the jaroslav@601: * reference type through which the method invocation occurred. jaroslav@601: * jaroslav@601: *
If a proxy interface contains a method with the same name and jaroslav@601: * parameter signature as the {@code hashCode}, {@code equals}, jaroslav@601: * or {@code toString} methods of {@code java.lang.Object}, jaroslav@601: * when such a method is invoked on a proxy instance, the jaroslav@601: * {@code Method} object passed to the invocation handler will have jaroslav@601: * {@code java.lang.Object} as its declaring class. In other words, jaroslav@601: * the public, non-final methods of {@code java.lang.Object} jaroslav@601: * logically precede all of the proxy interfaces for the determination of jaroslav@601: * which {@code Method} object to pass to the invocation handler. jaroslav@601: * jaroslav@601: *
Note also that when a duplicate method is dispatched to an
jaroslav@601: * invocation handler, the {@code invoke} method may only throw
jaroslav@601: * checked exception types that are assignable to one of the exception
jaroslav@601: * types in the {@code throws} clause of the method in all of
jaroslav@601: * the proxy interfaces that it can be invoked through. If the
jaroslav@601: * {@code invoke} method throws a checked exception that is not
jaroslav@601: * assignable to any of the exception types declared by the method in one
jaroslav@601: * of the proxy interfaces that it can be invoked through, then an
jaroslav@601: * unchecked {@code UndeclaredThrowableException} will be thrown by
jaroslav@601: * the invocation on the proxy instance. This restriction means that not
jaroslav@601: * all of the exception types returned by invoking
jaroslav@601: * {@code getExceptionTypes} on the {@code Method} object
jaroslav@601: * passed to the {@code invoke} method can necessarily be thrown
jaroslav@601: * successfully by the {@code invoke} method.
jaroslav@601: *
jaroslav@601: * @author Peter Jones
jaroslav@601: * @see InvocationHandler
jaroslav@601: * @since 1.3
jaroslav@601: */
jaroslav@601: public class Proxy implements java.io.Serializable {
jaroslav@601:
jaroslav@601: private static final long serialVersionUID = -2222568056686623797L;
jaroslav@601:
jaroslav@601: /** prefix for all proxy class names */
jaroslav@601: private final static String proxyClassNamePrefix = "$Proxy";
jaroslav@601:
jaroslav@601: /** parameter types of a proxy class constructor */
jaroslav@601: private final static Class[] constructorParams =
jaroslav@601: { InvocationHandler.class };
jaroslav@601:
jaroslav@601: /** maps a class loader to the proxy class cache for that loader */
jaroslav@601: private static Map There are several restrictions on the parameters that may be
jaroslav@601: * passed to {@code Proxy.getProxyClass}:
jaroslav@601: *
jaroslav@601: * If any of these restrictions are violated,
jaroslav@601: * {@code Proxy.getProxyClass} will throw an
jaroslav@601: * {@code IllegalArgumentException}. If the {@code interfaces}
jaroslav@601: * array argument or any of its elements are {@code null}, a
jaroslav@601: * {@code NullPointerException} will be thrown.
jaroslav@601: *
jaroslav@601: * Note that the order of the specified proxy interfaces is
jaroslav@601: * significant: two requests for a proxy class with the same combination
jaroslav@601: * of interfaces but in a different order will result in two distinct
jaroslav@601: * proxy classes.
jaroslav@601: *
jaroslav@601: * @param loader the class loader to define the proxy class
jaroslav@601: * @param interfaces the list of interfaces for the proxy class
jaroslav@601: * to implement
jaroslav@601: * @return a proxy class that is defined in the specified class loader
jaroslav@601: * and that implements the specified interfaces
jaroslav@601: * @throws IllegalArgumentException if any of the restrictions on the
jaroslav@601: * parameters that may be passed to {@code getProxyClass}
jaroslav@601: * are violated
jaroslav@601: * @throws NullPointerException if the {@code interfaces} array
jaroslav@601: * argument or any of its elements are {@code null}
jaroslav@601: */
jaroslav@601: public static Class> getProxyClass(ClassLoader loader,
jaroslav@601: Class>... interfaces)
jaroslav@601: throws IllegalArgumentException
jaroslav@601: {
jaroslav@601: if (interfaces.length > 65535) {
jaroslav@601: throw new IllegalArgumentException("interface limit exceeded");
jaroslav@601: }
jaroslav@601:
jaroslav@601: Class> proxyClass = null;
jaroslav@601:
jaroslav@601: /* collect interface names to use as key for proxy class cache */
jaroslav@601: String[] interfaceNames = new String[interfaces.length];
jaroslav@601:
jaroslav@601: // for detecting duplicates
jaroslav@601: Set {@code Proxy.newProxyInstance} throws
jaroslav@601: * {@code IllegalArgumentException} for the same reasons that
jaroslav@601: * {@code Proxy.getProxyClass} does.
jaroslav@601: *
jaroslav@601: * @param loader the class loader to define the proxy class
jaroslav@601: * @param interfaces the list of interfaces for the proxy class
jaroslav@601: * to implement
jaroslav@601: * @param h the invocation handler to dispatch method invocations to
jaroslav@601: * @return a proxy instance with the specified invocation handler of a
jaroslav@601: * proxy class that is defined by the specified class loader
jaroslav@601: * and that implements the specified interfaces
jaroslav@601: * @throws IllegalArgumentException if any of the restrictions on the
jaroslav@601: * parameters that may be passed to {@code getProxyClass}
jaroslav@601: * are violated
jaroslav@601: * @throws NullPointerException if the {@code interfaces} array
jaroslav@601: * argument or any of its elements are {@code null}, or
jaroslav@601: * if the invocation handler, {@code h}, is
jaroslav@601: * {@code null}
jaroslav@601: */
jaroslav@601: public static Object newProxyInstance(ClassLoader loader,
jaroslav@601: Class>[] interfaces,
jaroslav@601: InvocationHandler h)
jaroslav@601: throws IllegalArgumentException
jaroslav@601: {
jaroslav@601: if (h == null) {
jaroslav@601: throw new NullPointerException();
jaroslav@601: }
jaroslav@601:
jaroslav@601: /*
jaroslav@601: * Look up or generate the designated proxy class.
jaroslav@601: */
jaroslav@601: Class> cl = getProxyClass(loader, interfaces);
jaroslav@601:
jaroslav@601: /*
jaroslav@601: * Invoke its constructor with the designated invocation handler.
jaroslav@601: */
jaroslav@601: try {
jaroslav@601: Constructor cons = cl.getConstructor(constructorParams);
jaroslav@601: return cons.newInstance(new Object[] { h });
jaroslav@601: } catch (NoSuchMethodException e) {
jaroslav@601: throw new InternalError(e.toString());
jaroslav@601: } catch (IllegalAccessException e) {
jaroslav@601: throw new InternalError(e.toString());
jaroslav@601: } catch (InstantiationException e) {
jaroslav@601: throw new InternalError(e.toString());
jaroslav@601: } catch (InvocationTargetException e) {
jaroslav@601: throw new InternalError(e.toString());
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Returns true if and only if the specified class was dynamically
jaroslav@601: * generated to be a proxy class using the {@code getProxyClass}
jaroslav@601: * method or the {@code newProxyInstance} method.
jaroslav@601: *
jaroslav@601: * The reliability of this method is important for the ability
jaroslav@601: * to use it to make security decisions, so its implementation should
jaroslav@601: * not just test if the class in question extends {@code Proxy}.
jaroslav@601: *
jaroslav@601: * @param cl the class to test
jaroslav@601: * @return {@code true} if the class is a proxy class and
jaroslav@601: * {@code false} otherwise
jaroslav@601: * @throws NullPointerException if {@code cl} is {@code null}
jaroslav@601: */
jaroslav@601: public static boolean isProxyClass(Class> cl) {
jaroslav@601: if (cl == null) {
jaroslav@601: throw new NullPointerException();
jaroslav@601: }
jaroslav@601:
jaroslav@601: return proxyClasses.containsKey(cl);
jaroslav@601: }
jaroslav@601:
jaroslav@601: /**
jaroslav@601: * Returns the invocation handler for the specified proxy instance.
jaroslav@601: *
jaroslav@601: * @param proxy the proxy instance to return the invocation handler for
jaroslav@601: * @return the invocation handler for the proxy instance
jaroslav@601: * @throws IllegalArgumentException if the argument is not a
jaroslav@601: * proxy instance
jaroslav@601: */
jaroslav@601: public static InvocationHandler getInvocationHandler(Object proxy)
jaroslav@601: throws IllegalArgumentException
jaroslav@601: {
jaroslav@601: /*
jaroslav@601: * Verify that the object is actually a proxy instance.
jaroslav@601: */
jaroslav@601: if (!isProxyClass(proxy.getClass())) {
jaroslav@601: throw new IllegalArgumentException("not a proxy instance");
jaroslav@601: }
jaroslav@601:
jaroslav@601: Proxy p = (Proxy) proxy;
jaroslav@601: return p.h;
jaroslav@601: }
jaroslav@601:
jaroslav@601: private static native Class defineClass0(ClassLoader loader, String name,
jaroslav@601: byte[] b, int off, int len);
jaroslav@601: }
jaroslav@601: *
jaroslav@601: *
jaroslav@601: *
jaroslav@601: * Class.forName(i.getName(), false, cl) == i
jaroslav@601: *
jaroslav@601: *
jaroslav@601: *
jaroslav@601: *
jaroslav@601: *
jaroslav@601: * , Object> cache;
jaroslav@601: synchronized (loaderToCache) {
jaroslav@601: cache = loaderToCache.get(loader);
jaroslav@601: if (cache == null) {
jaroslav@601: cache = new HashMap<>();
jaroslav@601: loaderToCache.put(loader, cache);
jaroslav@601: }
jaroslav@601: /*
jaroslav@601: * This mapping will remain valid for the duration of this
jaroslav@601: * method, without further synchronization, because the mapping
jaroslav@601: * will only be removed if the class loader becomes unreachable.
jaroslav@601: */
jaroslav@601: }
jaroslav@601:
jaroslav@601: /*
jaroslav@601: * Look up the list of interfaces in the proxy class cache using
jaroslav@601: * the key. This lookup will result in one of three possible
jaroslav@601: * kinds of values:
jaroslav@601: * null, if there is currently no proxy class for the list of
jaroslav@601: * interfaces in the class loader,
jaroslav@601: * the pendingGenerationMarker object, if a proxy class for the
jaroslav@601: * list of interfaces is currently being generated,
jaroslav@601: * or a weak reference to a Class object, if a proxy class for
jaroslav@601: * the list of interfaces has already been generated.
jaroslav@601: */
jaroslav@601: synchronized (cache) {
jaroslav@601: /*
jaroslav@601: * Note that we need not worry about reaping the cache for
jaroslav@601: * entries with cleared weak references because if a proxy class
jaroslav@601: * has been garbage collected, its class loader will have been
jaroslav@601: * garbage collected as well, so the entire cache will be reaped
jaroslav@601: * from the loaderToCache map.
jaroslav@601: */
jaroslav@601: do {
jaroslav@601: Object value = cache.get(key);
jaroslav@601: if (value instanceof Reference) {
jaroslav@601: proxyClass = (Class>) ((Reference) value).get();
jaroslav@601: }
jaroslav@601: if (proxyClass != null) {
jaroslav@601: // proxy class already generated: return it
jaroslav@601: return proxyClass;
jaroslav@601: } else if (value == pendingGenerationMarker) {
jaroslav@601: // proxy class being generated: wait for it
jaroslav@601: try {
jaroslav@601: cache.wait();
jaroslav@601: } catch (InterruptedException e) {
jaroslav@601: /*
jaroslav@601: * The class generation that we are waiting for should
jaroslav@601: * take a small, bounded time, so we can safely ignore
jaroslav@601: * thread interrupts here.
jaroslav@601: */
jaroslav@601: }
jaroslav@601: continue;
jaroslav@601: } else {
jaroslav@601: /*
jaroslav@601: * No proxy class for this list of interfaces has been
jaroslav@601: * generated or is being generated, so we will go and
jaroslav@601: * generate it now. Mark it as pending generation.
jaroslav@601: */
jaroslav@601: cache.put(key, pendingGenerationMarker);
jaroslav@601: break;
jaroslav@601: }
jaroslav@601: } while (true);
jaroslav@601: }
jaroslav@601:
jaroslav@601: try {
jaroslav@601: String proxyPkg = null; // package to define proxy class in
jaroslav@601:
jaroslav@601: /*
jaroslav@601: * Record the package of a non-public proxy interface so that the
jaroslav@601: * proxy class will be defined in the same package. Verify that
jaroslav@601: * all non-public proxy interfaces are in the same package.
jaroslav@601: */
jaroslav@601: for (int i = 0; i < interfaces.length; i++) {
jaroslav@601: int flags = interfaces[i].getModifiers();
jaroslav@601: if (!Modifier.isPublic(flags)) {
jaroslav@601: String name = interfaces[i].getName();
jaroslav@601: int n = name.lastIndexOf('.');
jaroslav@601: String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
jaroslav@601: if (proxyPkg == null) {
jaroslav@601: proxyPkg = pkg;
jaroslav@601: } else if (!pkg.equals(proxyPkg)) {
jaroslav@601: throw new IllegalArgumentException(
jaroslav@601: "non-public interfaces from different packages");
jaroslav@601: }
jaroslav@601: }
jaroslav@601: }
jaroslav@601:
jaroslav@601: if (proxyPkg == null) { // if no non-public proxy interfaces,
jaroslav@601: proxyPkg = ""; // use the unnamed package
jaroslav@601: }
jaroslav@601:
jaroslav@601: {
jaroslav@601: /*
jaroslav@601: * Choose a name for the proxy class to generate.
jaroslav@601: */
jaroslav@601: long num;
jaroslav@601: synchronized (nextUniqueNumberLock) {
jaroslav@601: num = nextUniqueNumber++;
jaroslav@601: }
jaroslav@601: String proxyName = proxyPkg + proxyClassNamePrefix + num;
jaroslav@601: /*
jaroslav@601: * Verify that the class loader hasn't already
jaroslav@601: * defined a class with the chosen name.
jaroslav@601: */
jaroslav@601:
jaroslav@601: /*
jaroslav@601: * Generate the specified proxy class.
jaroslav@601: */
jaroslav@601: byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
jaroslav@601: proxyName, interfaces);
jaroslav@601: try {
jaroslav@601: proxyClass = defineClass0(loader, proxyName,
jaroslav@601: proxyClassFile, 0, proxyClassFile.length);
jaroslav@601: } catch (ClassFormatError e) {
jaroslav@601: /*
jaroslav@601: * A ClassFormatError here means that (barring bugs in the
jaroslav@601: * proxy class generation code) there was some other
jaroslav@601: * invalid aspect of the arguments supplied to the proxy
jaroslav@601: * class creation (such as virtual machine limitations
jaroslav@601: * exceeded).
jaroslav@601: */
jaroslav@601: throw new IllegalArgumentException(e.toString());
jaroslav@601: }
jaroslav@601: }
jaroslav@601: // add to set of all generated proxy classes, for isProxyClass
jaroslav@601: proxyClasses.put(proxyClass, null);
jaroslav@601:
jaroslav@601: } finally {
jaroslav@601: /*
jaroslav@601: * We must clean up the "pending generation" state of the proxy
jaroslav@601: * class cache entry somehow. If a proxy class was successfully
jaroslav@601: * generated, store it in the cache (with a weak reference);
jaroslav@601: * otherwise, remove the reserved entry. In all cases, notify
jaroslav@601: * all waiters on reserved entries in this cache.
jaroslav@601: */
jaroslav@601: synchronized (cache) {
jaroslav@601: if (proxyClass != null) {
jaroslav@601: cache.put(key, new WeakReference
jaroslav@601: * Proxy.getProxyClass(loader, interfaces).
jaroslav@601: * getConstructor(new Class[] { InvocationHandler.class }).
jaroslav@601: * newInstance(new Object[] { handler });
jaroslav@601: *
jaroslav@601: *
jaroslav@601: *