Lookup.java revision 1551:f3b883bec2d0
1/*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/*
27 * This file is available under and governed by the GNU General Public
28 * License version 2 only, as published by the Free Software Foundation.
29 * However, the following notice accompanied the original version of this
30 * file, and Oracle licenses the original version of this file under the BSD
31 * license:
32 */
33/*
34   Copyright 2009-2013 Attila Szegedi
35
36   Licensed under both the Apache License, Version 2.0 (the "Apache License")
37   and the BSD License (the "BSD License"), with licensee being free to
38   choose either of the two at their discretion.
39
40   You may not use this file except in compliance with either the Apache
41   License or the BSD License.
42
43   If you choose to use this file in compliance with the Apache License, the
44   following notice applies to you:
45
46       You may obtain a copy of the Apache License at
47
48           http://www.apache.org/licenses/LICENSE-2.0
49
50       Unless required by applicable law or agreed to in writing, software
51       distributed under the License is distributed on an "AS IS" BASIS,
52       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
53       implied. See the License for the specific language governing
54       permissions and limitations under the License.
55
56   If you choose to use this file in compliance with the BSD License, the
57   following notice applies to you:
58
59       Redistribution and use in source and binary forms, with or without
60       modification, are permitted provided that the following conditions are
61       met:
62       * Redistributions of source code must retain the above copyright
63         notice, this list of conditions and the following disclaimer.
64       * Redistributions in binary form must reproduce the above copyright
65         notice, this list of conditions and the following disclaimer in the
66         documentation and/or other materials provided with the distribution.
67       * Neither the name of the copyright holder nor the names of
68         contributors may be used to endorse or promote products derived from
69         this software without specific prior written permission.
70
71       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
72       IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
73       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
74       PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
75       BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
76       CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
77       SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
78       BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
79       WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
80       OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
81       ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
82*/
83
84package jdk.dynalink.linker.support;
85
86import java.lang.invoke.MethodHandle;
87import java.lang.invoke.MethodHandles;
88import java.lang.invoke.MethodType;
89import java.lang.reflect.Constructor;
90import java.lang.reflect.Field;
91import java.lang.reflect.Method;
92
93/**
94 * A wrapper around {@link java.lang.invoke.MethodHandles.Lookup} that masks
95 * checked exceptions. It is useful in those cases when you're looking up
96 * methods within your own codebase (therefore it is an error if they are not
97 * present).
98 */
99public final class Lookup {
100    private final MethodHandles.Lookup lookup;
101
102    /**
103     * Creates a new instance, bound to an instance of
104     * {@link java.lang.invoke.MethodHandles.Lookup}.
105     *
106     * @param lookup the {@link java.lang.invoke.MethodHandles.Lookup} it delegates to.
107     */
108    public Lookup(final MethodHandles.Lookup lookup) {
109        this.lookup = lookup;
110    }
111
112    /**
113     * A canonical Lookup object that wraps {@link MethodHandles#publicLookup()}.
114     */
115    public static final Lookup PUBLIC = new Lookup(MethodHandles.publicLookup());
116
117    /**
118     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflect(Method)},
119     * converting any encountered {@link IllegalAccessException} into an
120     * {@link IllegalAccessError}.
121     *
122     * @param m the method to unreflect
123     * @return the unreflected method handle.
124     * @throws IllegalAccessError if the method is inaccessible.
125     */
126    public MethodHandle unreflect(final Method m) {
127        return unreflect(lookup, m);
128    }
129
130    /**
131     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflect(Method)},
132     * converting any encountered {@link IllegalAccessException} into an
133     * {@link IllegalAccessError}.
134     *
135     * @param lookup the lookup used to unreflect
136     * @param m the method to unreflect
137     * @return the unreflected method handle.
138     * @throws IllegalAccessError if the method is inaccessible.
139     */
140    public static MethodHandle unreflect(final MethodHandles.Lookup lookup, final Method m) {
141        try {
142            return lookup.unreflect(m);
143        } catch(final IllegalAccessException e) {
144            final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect method " + m);
145            ee.initCause(e);
146            throw ee;
147        }
148    }
149
150    /**
151     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter(Field)},
152     * converting any encountered {@link IllegalAccessException} into an {@link IllegalAccessError}.
153     *
154     * @param f the field for which a getter is unreflected
155     * @return the unreflected field getter handle.
156     * @throws IllegalAccessError if the getter is inaccessible.
157     */
158    public MethodHandle unreflectGetter(final Field f) {
159        try {
160            return lookup.unreflectGetter(f);
161        } catch(final IllegalAccessException e) {
162            final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect getter for field " + f);
163            ee.initCause(e);
164            throw ee;
165        }
166    }
167
168    /**
169     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#findGetter(Class, String, Class)},
170     * converting any encountered {@link IllegalAccessException} into an
171     * {@link IllegalAccessError} and {@link NoSuchFieldException} into a
172     * {@link NoSuchFieldError}.
173     *
174     * @param refc the class declaring the field
175     * @param name the name of the field
176     * @param type the type of the field
177     * @return the unreflected field getter handle.
178     * @throws IllegalAccessError if the field is inaccessible.
179     * @throws NoSuchFieldError if the field does not exist.
180     */
181    public MethodHandle findGetter(final Class<?>refc, final String name, final Class<?> type) {
182        try {
183            return lookup.findGetter(refc, name, type);
184        } catch(final IllegalAccessException e) {
185            final IllegalAccessError ee = new IllegalAccessError("Failed to access getter for field " + refc.getName() +
186                    "." + name + " of type " + type.getName());
187            ee.initCause(e);
188            throw ee;
189        } catch(final NoSuchFieldException e) {
190            final NoSuchFieldError ee = new NoSuchFieldError("Failed to find getter for field " + refc.getName() +
191                    "." + name + " of type " + type.getName());
192            ee.initCause(e);
193            throw ee;
194        }
195    }
196
197    /**
198     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter(Field)},
199     * converting any encountered {@link IllegalAccessException} into an
200     * {@link IllegalAccessError}.
201     *
202     * @param f the field for which a setter is unreflected
203     * @return the unreflected field setter handle.
204     * @throws IllegalAccessError if the field is inaccessible.
205     * @throws NoSuchFieldError if the field does not exist.
206     */
207    public MethodHandle unreflectSetter(final Field f) {
208        try {
209            return lookup.unreflectSetter(f);
210        } catch(final IllegalAccessException e) {
211            final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect setter for field " + f);
212            ee.initCause(e);
213            throw ee;
214        }
215    }
216
217    /**
218     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor(Constructor)},
219     * converting any encountered {@link IllegalAccessException} into an
220     * {@link IllegalAccessError}.
221     *
222     * @param c the constructor to unreflect
223     * @return the unreflected constructor handle.
224     * @throws IllegalAccessError if the constructor is inaccessible.
225     */
226    public MethodHandle unreflectConstructor(final Constructor<?> c) {
227        return unreflectConstructor(lookup, c);
228    }
229
230    /**
231     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor(Constructor)},
232     * converting any encountered {@link IllegalAccessException} into an
233     * {@link IllegalAccessError}.
234     *
235     * @param lookup the lookup used to unreflect
236     * @param c the constructor to unreflect
237     * @return the unreflected constructor handle.
238     * @throws IllegalAccessError if the constructor is inaccessible.
239     */
240    public static MethodHandle unreflectConstructor(final MethodHandles.Lookup lookup, final Constructor<?> c) {
241        try {
242            return lookup.unreflectConstructor(c);
243        } catch(final IllegalAccessException e) {
244            final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect constructor " + c);
245            ee.initCause(e);
246            throw ee;
247        }
248    }
249
250    /**
251     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#findSpecial(Class, String, MethodType, Class)}
252     * on the underlying lookup. Converts any encountered
253     * {@link IllegalAccessException} into an {@link IllegalAccessError} and
254     * {@link NoSuchMethodException} into a {@link NoSuchMethodError}.
255     *
256     * @param declaringClass class declaring the method
257     * @param name the name of the method
258     * @param type the type of the method
259     * @return a method handle for the method
260     * @throws IllegalAccessError if the method is inaccessible.
261     * @throws NoSuchMethodError if the method does not exist.
262     */
263    public MethodHandle findSpecial(final Class<?> declaringClass, final String name, final MethodType type) {
264        try {
265            return lookup.findSpecial(declaringClass, name, type, declaringClass);
266        } catch(final IllegalAccessException e) {
267            final IllegalAccessError ee = new IllegalAccessError("Failed to access special method " + methodDescription(
268                    declaringClass, name, type));
269            ee.initCause(e);
270            throw ee;
271        } catch(final NoSuchMethodException e) {
272            final NoSuchMethodError ee = new NoSuchMethodError("Failed to find special method " + methodDescription(
273                    declaringClass, name, type));
274            ee.initCause(e);
275            throw ee;
276        }
277    }
278
279    private static String methodDescription(final Class<?> declaringClass, final String name, final MethodType type) {
280        return declaringClass.getName() + "#" + name + type;
281    }
282
283    /**
284     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#findStatic(Class, String, MethodType)}
285     * on the underlying lookup. Converts any encountered
286     * {@link IllegalAccessException} into an {@link IllegalAccessError} and
287     * {@link NoSuchMethodException} into a {@link NoSuchMethodError}.
288     *
289     * @param declaringClass class declaring the method
290     * @param name the name of the method
291     * @param type the type of the method
292     * @return a method handle for the method
293     * @throws IllegalAccessError if the method is inaccessible.
294     * @throws NoSuchMethodError if the method does not exist.
295     */
296    public MethodHandle findStatic(final Class<?> declaringClass, final String name, final MethodType type) {
297        try {
298            return lookup.findStatic(declaringClass, name, type);
299        } catch(final IllegalAccessException e) {
300            final IllegalAccessError ee = new IllegalAccessError("Failed to access static method " + methodDescription(
301                    declaringClass, name, type));
302            ee.initCause(e);
303            throw ee;
304        } catch(final NoSuchMethodException e) {
305            final NoSuchMethodError ee = new NoSuchMethodError("Failed to find static method " + methodDescription(
306                    declaringClass, name, type));
307            ee.initCause(e);
308            throw ee;
309        }
310    }
311
312    /**
313     * Performs a {@link java.lang.invoke.MethodHandles.Lookup#findVirtual(Class, String, MethodType)}
314     * on the underlying lookup. Converts any encountered
315     * {@link IllegalAccessException} into an {@link IllegalAccessError} and
316     * {@link NoSuchMethodException} into a {@link NoSuchMethodError}.
317     *
318     * @param declaringClass class declaring the method
319     * @param name the name of the method
320     * @param type the type of the method
321     * @return a method handle for the method
322     * @throws IllegalAccessError if the method is inaccessible.
323     * @throws NoSuchMethodError if the method does not exist.
324     */
325    public MethodHandle findVirtual(final Class<?> declaringClass, final String name, final MethodType type) {
326        try {
327            return lookup.findVirtual(declaringClass, name, type);
328        } catch(final IllegalAccessException e) {
329            final IllegalAccessError ee = new IllegalAccessError("Failed to access virtual method " + methodDescription(
330                    declaringClass, name, type));
331            ee.initCause(e);
332            throw ee;
333        } catch(final NoSuchMethodException e) {
334            final NoSuchMethodError ee = new NoSuchMethodError("Failed to find virtual method " + methodDescription(
335                    declaringClass, name, type));
336            ee.initCause(e);
337            throw ee;
338        }
339    }
340
341    /**
342     * Given a lookup, finds using {@link #findSpecial(Class, String, MethodType)}
343     * a method on that lookup's class. Useful in classes' code for convenient
344     * linking to their own privates.
345     * @param lookup the lookup for the class
346     * @param name the name of the method
347     * @param rtype the return type of the method
348     * @param ptypes the parameter types of the method
349     * @return the method handle for the method
350     */
351    public static MethodHandle findOwnSpecial(final MethodHandles.Lookup lookup, final String name, final Class<?> rtype, final Class<?>... ptypes) {
352        return new Lookup(lookup).findOwnSpecial(name, rtype, ptypes);
353    }
354
355
356    /**
357     * Finds using {@link #findSpecial(Class, String, MethodType)} a method on
358     * that lookup's class. Useful in classes' code for convenient linking to
359     * their own privates. It's also more convenient than {@code findSpecial}
360     * in that you can just list the parameter types, and don't have to specify
361     * lookup class.
362     * @param name the name of the method
363     * @param rtype the return type of the method
364     * @param ptypes the parameter types of the method
365     * @return the method handle for the method
366     */
367    public MethodHandle findOwnSpecial(final String name, final Class<?> rtype, final Class<?>... ptypes) {
368        return findSpecial(lookup.lookupClass(), name, MethodType.methodType(rtype, ptypes));
369    }
370
371    /**
372     * Given a lookup, finds using {@link #findStatic(Class, String, MethodType)}
373     * a method on that lookup's class. Useful in classes' code for convenient
374     * linking to their own privates. It's easier to use than {@code findStatic}
375     * in that you can just list the parameter types, and don't have to specify
376     * lookup class.
377     * @param lookup the lookup for the class
378     * @param name the name of the method
379     * @param rtype the return type of the method
380     * @param ptypes the parameter types of the method
381     * @return the method handle for the method
382     */
383    public static MethodHandle findOwnStatic(final MethodHandles.Lookup lookup, final String name, final Class<?> rtype, final Class<?>... ptypes) {
384        return new Lookup(lookup).findOwnStatic(name, rtype, ptypes);
385    }
386
387    /**
388     * Finds using {@link #findStatic(Class, String, MethodType)} a method on
389     * that lookup's class. Useful in classes' code for convenient linking to
390     * their own privates. It's easier to use than {@code findStatic}
391     * in that you can just list the parameter types, and don't have to specify
392     * lookup class.
393     * @param name the name of the method
394     * @param rtype the return type of the method
395     * @param ptypes the parameter types of the method
396     * @return the method handle for the method
397     */
398    public MethodHandle findOwnStatic(final String name, final Class<?> rtype, final Class<?>... ptypes) {
399        return findStatic(lookup.lookupClass(), name, MethodType.methodType(rtype, ptypes));
400    }
401}
402