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 
84 package jdk.internal.dynalink.support;
85 
86 import java.lang.invoke.MethodHandle;
87 import java.lang.invoke.MethodHandles;
88 import java.lang.invoke.MethodType;
89 import java.lang.reflect.Constructor;
90 import java.lang.reflect.Field;
91 import java.lang.reflect.Method;
92 
93 /**
94  * A wrapper around MethodHandles.Lookup that masks checked exceptions in those cases when you're looking up methods
95  * within your own codebase (therefore it is an error if they are not present).
96  *
97  * @author Attila Szegedi
98  */
99 public class Lookup {
100     private final MethodHandles.Lookup lookup;
101 
102     /**
103      * Creates a new instance, bound to an instance of {@link java.lang.invoke.MethodHandles.Lookup}.
104      *
105      * @param lookup the {@link java.lang.invoke.MethodHandles.Lookup} it delegates to.
106      */
Lookup(final MethodHandles.Lookup lookup)107     public Lookup(final MethodHandles.Lookup lookup) {
108         this.lookup = lookup;
109     }
110 
111     /**
112      * A canonical Lookup object that wraps {@link MethodHandles#publicLookup()}.
113      */
114     public static final Lookup PUBLIC = new Lookup(MethodHandles.publicLookup());
115 
116     /**
117      * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflect(Method)}, converting any encountered
118      * {@link IllegalAccessException} into an {@link IllegalAccessError}.
119      *
120      * @param m the method to unreflect
121      * @return the unreflected method handle.
122      */
unreflect(final Method m)123     public MethodHandle unreflect(final Method m) {
124         return unreflect(lookup, m);
125     }
126 
127     /**
128      * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflect(Method)}, converting any encountered
129      * {@link IllegalAccessException} into an {@link IllegalAccessError}.
130      *
131      * @param lookup the lookup used to unreflect
132      * @param m the method to unreflect
133      * @return the unreflected method handle.
134      */
unreflect(final MethodHandles.Lookup lookup, final Method m)135     public static MethodHandle unreflect(final MethodHandles.Lookup lookup, final Method m) {
136         try {
137             return lookup.unreflect(m);
138         } catch(final IllegalAccessException e) {
139             final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect method " + m);
140             ee.initCause(e);
141             throw ee;
142         }
143     }
144 
145     /**
146      * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectGetter(Field)}, converting any encountered
147      * {@link IllegalAccessException} into an {@link IllegalAccessError}.
148      *
149      * @param f the field for which a getter is unreflected
150      * @return the unreflected field getter handle.
151      */
unreflectGetter(final Field f)152     public MethodHandle unreflectGetter(final Field f) {
153         try {
154             return lookup.unreflectGetter(f);
155         } catch(final IllegalAccessException e) {
156             final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect getter for field " + f);
157             ee.initCause(e);
158             throw ee;
159         }
160     }
161 
162     /**
163      * Performs a {@link java.lang.invoke.MethodHandles.Lookup#findGetter(Class, String, Class)}, converting any
164      * encountered {@link IllegalAccessException} into an {@link IllegalAccessError} and {@link NoSuchFieldException}
165      * into a {@link NoSuchFieldError}.
166      *
167      * @param refc the class declaring the field
168      * @param name the name of the field
169      * @param type the type of the field
170      * @return the unreflected field getter handle.
171      * @throws IllegalAccessError if the field is inaccessible.
172      * @throws NoSuchFieldError if the field does not exist.
173      */
findGetter(final Class<?>refc, final String name, final Class<?> type)174     public MethodHandle findGetter(final Class<?>refc, final String name, final Class<?> type) {
175         try {
176             return lookup.findGetter(refc, name, type);
177         } catch(final IllegalAccessException e) {
178             final IllegalAccessError ee = new IllegalAccessError("Failed to access getter for field " + refc.getName() +
179                     "." + name + " of type " + type.getName());
180             ee.initCause(e);
181             throw ee;
182         } catch(final NoSuchFieldException e) {
183             final NoSuchFieldError ee = new NoSuchFieldError("Failed to find getter for field " + refc.getName() +
184                     "." + name + " of type " + type.getName());
185             ee.initCause(e);
186             throw ee;
187         }
188     }
189 
190     /**
191      * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectSetter(Field)}, converting any encountered
192      * {@link IllegalAccessException} into an {@link IllegalAccessError}.
193      *
194      * @param f the field for which a setter is unreflected
195      * @return the unreflected field setter handle.
196      */
unreflectSetter(final Field f)197     public MethodHandle unreflectSetter(final Field f) {
198         try {
199             return lookup.unreflectSetter(f);
200         } catch(final IllegalAccessException e) {
201             final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect setter for field " + f);
202             ee.initCause(e);
203             throw ee;
204         }
205     }
206 
207     /**
208      * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor(Constructor)}, converting any
209      * encountered {@link IllegalAccessException} into an {@link IllegalAccessError}.
210      *
211      * @param c the constructor to unreflect
212      * @return the unreflected constructor handle.
213      */
unreflectConstructor(final Constructor<?> c)214     public MethodHandle unreflectConstructor(final Constructor<?> c) {
215         return unreflectConstructor(lookup, c);
216     }
217 
218     /**
219      * Performs a {@link java.lang.invoke.MethodHandles.Lookup#unreflectConstructor(Constructor)}, converting any
220      * encountered {@link IllegalAccessException} into an {@link IllegalAccessError}.
221      *
222      * @param lookup the lookup used to unreflect
223      * @param c the constructor to unreflect
224      * @return the unreflected constructor handle.
225      */
unreflectConstructor(final MethodHandles.Lookup lookup, final Constructor<?> c)226     public static MethodHandle unreflectConstructor(final MethodHandles.Lookup lookup, final Constructor<?> c) {
227         try {
228             return lookup.unreflectConstructor(c);
229         } catch(final IllegalAccessException e) {
230             final IllegalAccessError ee = new IllegalAccessError("Failed to unreflect constructor " + c);
231             ee.initCause(e);
232             throw ee;
233         }
234     }
235 
236     /**
237      * Performs a findSpecial on the underlying lookup. Converts any encountered {@link IllegalAccessException} into an
238      * {@link IllegalAccessError} and a {@link NoSuchMethodException} into a {@link NoSuchMethodError}.
239      *
240      * @param declaringClass class declaring the method
241      * @param name the name of the method
242      * @param type the type of the method
243      * @return a method handle for the method
244      * @throws IllegalAccessError if the method is inaccessible.
245      * @throws NoSuchMethodError if the method does not exist.
246      */
findSpecial(final Class<?> declaringClass, final String name, final MethodType type)247     public MethodHandle findSpecial(final Class<?> declaringClass, final String name, final MethodType type) {
248         try {
249             return lookup.findSpecial(declaringClass, name, type, declaringClass);
250         } catch(final IllegalAccessException e) {
251             final IllegalAccessError ee = new IllegalAccessError("Failed to access special method " + methodDescription(
252                     declaringClass, name, type));
253             ee.initCause(e);
254             throw ee;
255         } catch(final NoSuchMethodException e) {
256             final NoSuchMethodError ee = new NoSuchMethodError("Failed to find special method " + methodDescription(
257                     declaringClass, name, type));
258             ee.initCause(e);
259             throw ee;
260         }
261     }
262 
methodDescription(final Class<?> declaringClass, final String name, final MethodType type)263     private static String methodDescription(final Class<?> declaringClass, final String name, final MethodType type) {
264         return declaringClass.getName() + "#" + name + type;
265     }
266 
267     /**
268      * Performs a findStatic on the underlying lookup. Converts any encountered {@link IllegalAccessException} into an
269      * {@link IllegalAccessError} and a {@link NoSuchMethodException} into a {@link NoSuchMethodError}.
270      *
271      * @param declaringClass class declaring the method
272      * @param name the name of the method
273      * @param type the type of the method
274      * @return a method handle for the method
275      * @throws IllegalAccessError if the method is inaccessible.
276      * @throws NoSuchMethodError if the method does not exist.
277      */
findStatic(final Class<?> declaringClass, final String name, final MethodType type)278     public MethodHandle findStatic(final Class<?> declaringClass, final String name, final MethodType type) {
279         try {
280             return lookup.findStatic(declaringClass, name, type);
281         } catch(final IllegalAccessException e) {
282             final IllegalAccessError ee = new IllegalAccessError("Failed to access static method " + methodDescription(
283                     declaringClass, name, type));
284             ee.initCause(e);
285             throw ee;
286         } catch(final NoSuchMethodException e) {
287             final NoSuchMethodError ee = new NoSuchMethodError("Failed to find static method " + methodDescription(
288                     declaringClass, name, type));
289             ee.initCause(e);
290             throw ee;
291         }
292     }
293 
294     /**
295      * Performs a findVirtual on the underlying lookup. Converts any encountered {@link IllegalAccessException} into an
296      * {@link IllegalAccessError} and a {@link NoSuchMethodException} into a {@link NoSuchMethodError}.
297      *
298      * @param declaringClass class declaring the method
299      * @param name the name of the method
300      * @param type the type of the method
301      * @return a method handle for the method
302      * @throws IllegalAccessError if the method is inaccessible.
303      * @throws NoSuchMethodError if the method does not exist.
304      */
findVirtual(final Class<?> declaringClass, final String name, final MethodType type)305     public MethodHandle findVirtual(final Class<?> declaringClass, final String name, final MethodType type) {
306         try {
307             return lookup.findVirtual(declaringClass, name, type);
308         } catch(final IllegalAccessException e) {
309             final IllegalAccessError ee = new IllegalAccessError("Failed to access virtual method " + methodDescription(
310                     declaringClass, name, type));
311             ee.initCause(e);
312             throw ee;
313         } catch(final NoSuchMethodException e) {
314             final NoSuchMethodError ee = new NoSuchMethodError("Failed to find virtual method " + methodDescription(
315                     declaringClass, name, type));
316             ee.initCause(e);
317             throw ee;
318         }
319     }
320 
321     /**
322      * Given a lookup, finds using {@link #findSpecial(Class, String, MethodType)} a method on that lookup's class.
323      * Useful in classes' code for convenient linking to their own privates.
324      * @param lookup the lookup for the class
325      * @param name the name of the method
326      * @param rtype the return type of the method
327      * @param ptypes the parameter types of the method
328      * @return the method handle for the method
329      */
findOwnSpecial(final MethodHandles.Lookup lookup, final String name, final Class<?> rtype, final Class<?>... ptypes)330     public static MethodHandle findOwnSpecial(final MethodHandles.Lookup lookup, final String name, final Class<?> rtype, final Class<?>... ptypes) {
331         return new Lookup(lookup).findOwnSpecial(name, rtype, ptypes);
332     }
333 
334 
335     /**
336      * Finds using {@link #findSpecial(Class, String, MethodType)} a method on that lookup's class. Useful in classes'
337      * code for convenient linking to their own privates. It's easier to use than {@code findSpecial} in that you can
338      * just list the parameter types, and don't have to specify lookup class.
339      * @param name the name of the method
340      * @param rtype the return type of the method
341      * @param ptypes the parameter types of the method
342      * @return the method handle for the method
343      */
findOwnSpecial(final String name, final Class<?> rtype, final Class<?>... ptypes)344     public MethodHandle findOwnSpecial(final String name, final Class<?> rtype, final Class<?>... ptypes) {
345         return findSpecial(lookup.lookupClass(), name, MethodType.methodType(rtype, ptypes));
346     }
347 
348     /**
349      * Given a lookup, finds using {@link #findStatic(Class, String, MethodType)} a method on that lookup's class.
350      * Useful in classes' code for convenient linking to their own privates. It's easier to use than {@code findStatic}
351      * in that you can just list the parameter types, and don't have to specify lookup class.
352      * @param lookup the lookup for the class
353      * @param name the name of the method
354      * @param rtype the return type of the method
355      * @param ptypes the parameter types of the method
356      * @return the method handle for the method
357      */
findOwnStatic(final MethodHandles.Lookup lookup, final String name, final Class<?> rtype, final Class<?>... ptypes)358     public static MethodHandle findOwnStatic(final MethodHandles.Lookup lookup, final String name, final Class<?> rtype, final Class<?>... ptypes) {
359         return new Lookup(lookup).findOwnStatic(name, rtype, ptypes);
360     }
361 
362     /**
363      * Finds using {@link #findStatic(Class, String, MethodType)} a method on that lookup's class. Useful in classes'
364      * code for convenient linking to their own privates. It's easier to use than {@code findStatic} in that you can
365      * just list the parameter types, and don't have to specify lookup class.
366      * @param name the name of the method
367      * @param rtype the return type of the method
368      * @param ptypes the parameter types of the method
369      * @return the method handle for the method
370      */
findOwnStatic(final String name, final Class<?> rtype, final Class<?>... ptypes)371     public MethodHandle findOwnStatic(final String name, final Class<?> rtype, final Class<?>... ptypes) {
372         return findStatic(lookup.lookupClass(), name, MethodType.methodType(rtype, ptypes));
373     }
374 }
375