MethodUtil.java 13.3 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 */

package sun.reflect.misc;

import java.security.AllPermission;
import java.security.AccessController;
import java.security.PermissionCollection;
import java.security.SecureClassLoader;
import java.security.PrivilegedExceptionAction;
import java.security.CodeSource;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
45
import sun.misc.IOUtils;
D
duke 已提交
46 47 48


class Trampoline {
S
smarks 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    static {
        if (Trampoline.class.getClassLoader() == null) {
            throw new Error(
                "Trampoline must not be defined by the bootstrap classloader");
        }
    }

    private static void ensureInvocableMethod(Method m)
        throws InvocationTargetException
    {
        Class<?> clazz = m.getDeclaringClass();
        if (clazz.equals(AccessController.class) ||
            clazz.equals(Method.class) ||
            clazz.getName().startsWith("java.lang.invoke."))
            throw new InvocationTargetException(
                new UnsupportedOperationException("invocation not supported"));
    }

D
duke 已提交
67
    private static Object invoke(Method m, Object obj, Object[] params)
S
smarks 已提交
68 69 70
        throws InvocationTargetException, IllegalAccessException
    {
        ensureInvocableMethod(m);
D
duke 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
        return m.invoke(obj, params);
    }
}

/*
 * Create a trampoline class.
 */
public final class MethodUtil extends SecureClassLoader {
    private static String MISC_PKG = "sun.reflect.misc.";
    private static String TRAMPOLINE = MISC_PKG + "Trampoline";
    private static Method bounce = getTrampoline();

    private MethodUtil() {
        super();
    }

87
    public static Method getMethod(Class<?> cls, String name, Class<?>[] args)
D
duke 已提交
88 89 90 91 92
        throws NoSuchMethodException {
        ReflectUtil.checkPackageAccess(cls);
        return cls.getMethod(name, args);
    }

93
    public static Method[] getMethods(Class<?> cls) {
D
duke 已提交
94 95 96 97 98 99 100 101 102 103
        ReflectUtil.checkPackageAccess(cls);
        return cls.getMethods();
    }

    /*
     * Discover the public methods on public classes
     * and interfaces accessible to any caller by calling
     * Class.getMethods() and walking towards Object until
     * we're done.
     */
104
     public static Method[] getPublicMethods(Class<?> cls) {
D
duke 已提交
105 106 107 108
        // compatibility for update release
        if (System.getSecurityManager() == null) {
            return cls.getMethods();
        }
109
        Map<Signature, Method> sigs = new HashMap<Signature, Method>();
D
duke 已提交
110 111 112 113 114 115 116 117
        while (cls != null) {
            boolean done = getInternalPublicMethods(cls, sigs);
            if (done) {
                break;
            }
            getInterfaceMethods(cls, sigs);
            cls = cls.getSuperclass();
        }
118
        return sigs.values().toArray(new Method[sigs.size()]);
D
duke 已提交
119 120 121 122 123
    }

    /*
     * Process the immediate interfaces of this class or interface.
     */
124
    private static void getInterfaceMethods(Class<?> cls,
125
                                            Map<Signature, Method> sigs) {
126
        Class<?>[] intfs = cls.getInterfaces();
D
duke 已提交
127
        for (int i=0; i < intfs.length; i++) {
128
            Class<?> intf = intfs[i];
D
duke 已提交
129 130 131 132 133 134 135 136 137 138 139
            boolean done = getInternalPublicMethods(intf, sigs);
            if (!done) {
                getInterfaceMethods(intf, sigs);
            }
        }
    }

    /*
     *
     * Process the methods in this class or interface
     */
140
    private static boolean getInternalPublicMethods(Class<?> cls,
141
                                                    Map<Signature, Method> sigs) {
D
duke 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        Method[] methods = null;
        try {
            /*
             * This class or interface is non-public so we
             * can't use any of it's methods. Go back and
             * try again with a superclass or superinterface.
             */
            if (!Modifier.isPublic(cls.getModifiers())) {
                return false;
            }
            if (!ReflectUtil.isPackageAccessible(cls)) {
                return false;
            }

            methods = cls.getMethods();
        } catch (SecurityException se) {
            return false;
        }

        /*
         * Check for inherited methods with non-public
         * declaring classes. They might override and hide
         * methods from their superclasses or
         * superinterfaces.
         */
        boolean done = true;
        for (int i=0; i < methods.length; i++) {
169
            Class<?> dc = methods[i].getDeclaringClass();
D
duke 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
            if (!Modifier.isPublic(dc.getModifiers())) {
                done = false;
                break;
            }
        }

        if (done) {
            /*
             * We're done. Spray all the methods into
             * the list and then we're out of here.
             */
            for (int i=0; i < methods.length; i++) {
                addMethod(sigs, methods[i]);
            }
        } else {
            /*
             * Simulate cls.getDeclaredMethods() by
             * stripping away inherited methods.
             */
            for (int i=0; i < methods.length; i++) {
190
                Class<?> dc = methods[i].getDeclaringClass();
D
duke 已提交
191 192 193 194 195 196 197 198
                if (cls.equals(dc)) {
                    addMethod(sigs, methods[i]);
                }
            }
        }
        return done;
    }

199
    private static void addMethod(Map<Signature, Method> sigs, Method method) {
D
duke 已提交
200 201 202 203 204 205 206
        Signature signature = new Signature(method);
        if (!sigs.containsKey(signature)) {
            sigs.put(signature, method);
        } else if (!method.getDeclaringClass().isInterface()){
            /*
             * Superclasses beat interfaces.
             */
207
            Method old = sigs.get(signature);
D
duke 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
            if (old.getDeclaringClass().isInterface()) {
                sigs.put(signature, method);
            }
        }
    }

    /**
     * A class that represents the unique elements of a method that will be a
     * key in the method cache.
     */
    private static class Signature {
        private String methodName;
        private Class[] argClasses;

        private volatile int hashCode = 0;

        Signature(Method m) {
            this.methodName = m.getName();
            this.argClasses = m.getParameterTypes();
        }

        public boolean equals(Object o2) {
            if (this == o2) {
                return true;
            }
            Signature that = (Signature)o2;
            if (!(methodName.equals(that.methodName))) {
                return false;
            }
            if (argClasses.length != that.argClasses.length) {
                return false;
            }
            for (int i = 0; i < argClasses.length; i++) {
                if (!(argClasses[i] == that.argClasses[i])) {
                  return false;
                }
            }
            return true;
        }

        /**
         * Hash code computed using algorithm suggested in
         * Effective Java, Item 8.
         */
        public int hashCode() {
            if (hashCode == 0) {
                int result = 17;
                result = 37 * result + methodName.hashCode();
                if (argClasses != null) {
                    for (int i = 0; i < argClasses.length; i++) {
                        result = 37 * result + ((argClasses[i] == null) ? 0 :
                            argClasses[i].hashCode());
                    }
                }
                hashCode = result;
            }
            return hashCode;
        }
    }


    /*
     * Bounce through the trampoline.
     */
    public static Object invoke(Method m, Object obj, Object[] params)
        throws InvocationTargetException, IllegalAccessException {
        try {
            return bounce.invoke(null, new Object[] {m, obj, params});
        } catch (InvocationTargetException ie) {
            Throwable t = ie.getCause();

            if (t instanceof InvocationTargetException) {
                throw (InvocationTargetException)t;
            } else if (t instanceof IllegalAccessException) {
                throw (IllegalAccessException)t;
            } else if (t instanceof RuntimeException) {
                throw (RuntimeException)t;
            } else if (t instanceof Error) {
                throw (Error)t;
            } else {
                throw new Error("Unexpected invocation error", t);
            }
        } catch (IllegalAccessException iae) {
            // this can't happen
            throw new Error("Unexpected invocation error", iae);
        }
    }

    private static Method getTrampoline() {
        try {
298 299 300 301 302 303 304 305
            return AccessController.doPrivileged(
                new PrivilegedExceptionAction<Method>() {
                    public Method run() throws Exception {
                        Class<?> t = getTrampolineClass();
                        Class[] types = {
                            Method.class, Object.class, Object[].class
                        };
                        Method b = t.getDeclaredMethod("invoke", types);
S
smarks 已提交
306 307 308 309
                        b.setAccessible(true);
                        return b;
                    }
                });
D
duke 已提交
310
        } catch (Exception e) {
311
            throw new InternalError("bouncer cannot be found", e);
D
duke 已提交
312 313 314 315
        }
    }


316
    protected synchronized Class<?> loadClass(String name, boolean resolve)
D
duke 已提交
317 318 319 320
        throws ClassNotFoundException
    {
        // First, check if the class has already been loaded
        ReflectUtil.checkPackageAccess(name);
321
        Class<?> c = findLoadedClass(name);
D
duke 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        if (c == null) {
            try {
                c = findClass(name);
            } catch (ClassNotFoundException e) {
                // Fall through ...
            }
            if (c == null) {
                c = getParent().loadClass(name);
            }
        }
        if (resolve) {
            resolveClass(c);
        }
        return c;
    }


339
    protected Class<?> findClass(final String name)
D
duke 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        throws ClassNotFoundException
    {
        if (!name.startsWith(MISC_PKG)) {
            throw new ClassNotFoundException(name);
        }
        String path = name.replace('.', '/').concat(".class");
        URL res = getResource(path);
        if (res != null) {
            try {
                return defineClass(name, res);
            } catch (IOException e) {
                throw new ClassNotFoundException(name, e);
            }
        } else {
            throw new ClassNotFoundException(name);
        }
    }


    /*
     * Define the proxy classes
     */
362
    private Class<?> defineClass(String name, URL url) throws IOException {
D
duke 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        byte[] b = getBytes(url);
        CodeSource cs = new CodeSource(null, (java.security.cert.Certificate[])null);
        if (!name.equals(TRAMPOLINE)) {
            throw new IOException("MethodUtil: bad name " + name);
        }
        return defineClass(name, b, 0, b.length, cs);
    }


    /*
     * Returns the contents of the specified URL as an array of bytes.
     */
    private static byte[] getBytes(URL url) throws IOException {
        URLConnection uc = url.openConnection();
        if (uc instanceof java.net.HttpURLConnection) {
            java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
            int code = huc.getResponseCode();
            if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
                throw new IOException("open HTTP connection failed.");
            }
        }
        int len = uc.getContentLength();
        InputStream in = new BufferedInputStream(uc.getInputStream());

        byte[] b;
        try {
389
            b = IOUtils.readFully(in, len, true);
D
duke 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403
        } finally {
            in.close();
        }
        return b;
    }


    protected PermissionCollection getPermissions(CodeSource codesource)
    {
        PermissionCollection perms = super.getPermissions(codesource);
        perms.add(new AllPermission());
        return perms;
    }

404
    private static Class<?> getTrampolineClass() {
D
duke 已提交
405 406 407 408 409 410 411 412
        try {
            return Class.forName(TRAMPOLINE, true, new MethodUtil());
        } catch (ClassNotFoundException e) {
        }
        return null;
    }

}