1 /*
  2  * Copyright (c) 2012, 2020, 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 package java.lang.invoke;
 27 
 28 import java.lang.reflect.*;
 29 import java.util.*;
 30 import java.lang.invoke.MethodHandleNatives.Constants;
 31 import java.lang.invoke.MethodHandles.Lookup;
 32 import static java.lang.invoke.MethodHandleStatics.*;
 33 
 34 /**
 35  * A symbolic reference obtained by cracking a direct method handle
 36  * into its constituent symbolic parts.
 37  * To crack a direct method handle, call {@link Lookup#revealDirect Lookup.revealDirect}.
 38  * <h2><a id="directmh"></a>Direct Method Handles</h2>
 39  * A <em>direct method handle</em> represents a method, constructor, or field without
 40  * any intervening argument bindings or other transformations.
 41  * The method, constructor, or field referred to by a direct method handle is called
 42  * its <em>underlying member</em>.
 43  * Direct method handles may be obtained in any of these ways:
 44  * <ul>
 45  * <li>By executing an {@code ldc} instruction on a {@code CONSTANT_MethodHandle} constant.
 46  *     (See the Java Virtual Machine Specification, sections {@jvms
 47  *     4.4.8} and {@jvms 5.4.3}.)
 48  * <li>By calling one of the <a href="MethodHandles.Lookup.html#lookups">Lookup Factory Methods</a>,
 49  *     such as {@link Lookup#findVirtual Lookup.findVirtual},
 50  *     to resolve a symbolic reference into a method handle.
 51  *     A symbolic reference consists of a class, name string, and type.
 52  * <li>By calling the factory method {@link Lookup#unreflect Lookup.unreflect}
 53  *     or {@link Lookup#unreflectSpecial Lookup.unreflectSpecial}
 54  *     to convert a {@link Method} into a method handle.
 55  * <li>By calling the factory method {@link Lookup#unreflectConstructor Lookup.unreflectConstructor}
 56  *     to convert a {@link Constructor} into a method handle.
 57  * <li>By calling the factory method {@link Lookup#unreflectGetter Lookup.unreflectGetter}
 58  *     or {@link Lookup#unreflectSetter Lookup.unreflectSetter}
 59  *     to convert a {@link Field} into a method handle.
 60  * </ul>
 61  *
 62  * <h2>Restrictions on Cracking</h2>
 63  * Given a suitable {@code Lookup} object, it is possible to crack any direct method handle
 64  * to recover a symbolic reference for the underlying method, constructor, or field.
 65  * Cracking must be done via a {@code Lookup} object equivalent to that which created
 66  * the target method handle, or which has enough access permissions to recreate
 67  * an equivalent method handle.
 68  * <p>
 69  * If the underlying method is <a href="MethodHandles.Lookup.html#callsens">caller sensitive</a>,
 70  * the direct method handle will have been "bound" to a particular caller class, the
 71  * {@linkplain java.lang.invoke.MethodHandles.Lookup#lookupClass() lookup class}
 72  * of the lookup object used to create it.
 73  * Cracking this method handle with a different lookup class will fail
 74  * even if the underlying method is public (like {@code Class.forName}).
 75  * <p>
 76  * The requirement of lookup object matching provides a "fast fail" behavior
 77  * for programs which may otherwise trust erroneous revelation of a method
 78  * handle with symbolic information (or caller binding) from an unexpected scope.
 79  * Use {@link java.lang.invoke.MethodHandles#reflectAs} to override this limitation.
 80  *
 81  * <h2><a id="refkinds"></a>Reference kinds</h2>
 82  * The <a href="MethodHandles.Lookup.html#lookups">Lookup Factory Methods</a>
 83  * correspond to all major use cases for methods, constructors, and fields.
 84  * These use cases may be distinguished using small integers as follows:
 85  * <table class="striped">
 86  * <caption style="display:none">reference kinds</caption>
 87  * <thead>
 88  * <tr><th scope="col">reference kind</th><th scope="col">descriptive name</th><th scope="col">scope</th><th scope="col">member</th><th scope="col">behavior</th></tr>
 89  * </thead>
 90  * <tbody>
 91  * <tr>
 92  *     <th scope="row">{@code 1}</th><td>{@code REF_getField}</td><td>{@code class}</td>
 93  *     <td>{@code FT f;}</td><td>{@code (T) this.f;}</td>
 94  * </tr>
 95  * <tr>
 96  *     <th scope="row">{@code 2}</th><td>{@code REF_getStatic}</td><td>{@code class} or {@code interface}</td>
 97  *     <td>{@code static}<br>{@code FT f;}</td><td>{@code (T) C.f;}</td>
 98  * </tr>
 99  * <tr>
100  *     <th scope="row">{@code 3}</th><td>{@code REF_putField}</td><td>{@code class}</td>
101  *     <td>{@code FT f;}</td><td>{@code this.f = x;}</td>
102  * </tr>
103  * <tr>
104  *     <th scope="row">{@code 4}</th><td>{@code REF_putStatic}</td><td>{@code class}</td>
105  *     <td>{@code static}<br>{@code FT f;}</td><td>{@code C.f = arg;}</td>
106  * </tr>
107  * <tr>
108  *     <th scope="row">{@code 5}</th><td>{@code REF_invokeVirtual}</td><td>{@code class}</td>
109  *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
110  * </tr>
111  * <tr>
112  *     <th scope="row">{@code 6}</th><td>{@code REF_invokeStatic}</td><td>{@code class} or {@code interface}</td>
113  *     <td>{@code static}<br>{@code T m(A*);}</td><td>{@code (T) C.m(arg*);}</td>
114  * </tr>
115  * <tr>
116  *     <th scope="row">{@code 7}</th><td>{@code REF_invokeSpecial}</td><td>{@code class} or {@code interface}</td>
117  *     <td>{@code T m(A*);}</td><td>{@code (T) super.m(arg*);}</td>
118  * </tr>
119  * <tr>
120  *     <th scope="row">{@code 8}</th><td>{@code REF_newInvokeSpecial}</td><td>{@code class}</td>
121  *     <td>{@code C(A*);}</td><td>{@code new C(arg*);}</td>
122  * </tr>
123  * <tr>
124  *     <th scope="row">{@code 9}</th><td>{@code REF_invokeInterface}</td><td>{@code interface}</td>
125  *     <td>{@code T m(A*);}</td><td>{@code (T) this.m(arg*);}</td>
126  * </tr>
127  * </tbody>
128  * </table>
129  * @since 1.8
130  */
131 public interface MethodHandleInfo {
132     /**
133      * A direct method handle reference kind,
134      * as defined in the <a href="MethodHandleInfo.html#refkinds">table above</a>.
135      */
136     public static final int
137         REF_getField                = Constants.REF_getField,
138         REF_getStatic               = Constants.REF_getStatic,
139         REF_putField                = Constants.REF_putField,
140         REF_putStatic               = Constants.REF_putStatic,
141         REF_invokeVirtual           = Constants.REF_invokeVirtual,
142         REF_invokeStatic            = Constants.REF_invokeStatic,
143         REF_invokeSpecial           = Constants.REF_invokeSpecial,
144         REF_newInvokeSpecial        = Constants.REF_newInvokeSpecial,
145         REF_invokeInterface         = Constants.REF_invokeInterface;
146 
147     /**
148      * Returns the reference kind of the cracked method handle, which in turn
149      * determines whether the method handle's underlying member was a constructor, method, or field.
150      * See the <a href="MethodHandleInfo.html#refkinds">table above</a> for definitions.
151      * @return the integer code for the kind of reference used to access the underlying member
152      */
153     public int getReferenceKind();
154 
155     /**
156      * Returns the class in which the cracked method handle's underlying member was defined.
157      * @return the declaring class of the underlying member
158      */
159     public Class<?> getDeclaringClass();
160 
161     /**
162      * Returns the name of the cracked method handle's underlying member.
163      * This is {@code "<init>"} if the underlying member was a constructor,
164      * or {@code "<vnew>"} if the underlying member was a value class static
165      * factory method, else it is a simple method name or field name.
166      * was a constructor, else it is a simple method name or field name.
167      * @return the simple name of the underlying member
168      */
169     public String getName();
170 
171     /**
172      * Returns the nominal type of the cracked symbolic reference, expressed as a method type.
173      * If the reference is to a constructor, the return type will be {@code void}.
174      * If it is to a non-static method, the method type will not mention the {@code this} parameter.
175      * If it is to a field and the requested access is to read the field,
176      * the method type will have no parameters and return the field type.
177      * If it is to a field and the requested access is to write the field,
178      * the method type will have one parameter of the field type and return {@code void}.
179      * <p>
180      * Note that original direct method handle may include a leading {@code this} parameter,
181      * or (in the case of a constructor) will replace the {@code void} return type
182      * with the constructed class.
183      * The nominal type does not include any {@code this} parameter,
184      * and (in the case of a constructor) will return {@code void}.
185      * @return the type of the underlying member, expressed as a method type
186      */
187     public MethodType getMethodType();
188 
189     // Utility methods.
190     // NOTE: class/name/type and reference kind constitute a symbolic reference
191     // member and modifiers are an add-on, derived from Core Reflection (or the equivalent)
192 
193     /**
194      * Reflects the underlying member as a method, constructor, or field object.
195      * If the underlying member is public, it is reflected as if by
196      * {@code getMethod}, {@code getConstructor}, or {@code getField}.
197      * Otherwise, it is reflected as if by
198      * {@code getDeclaredMethod}, {@code getDeclaredConstructor}, or {@code getDeclaredField}.
199      * The underlying member must be accessible to the given lookup object.
200      * @param <T> the desired type of the result, either {@link Member} or a subtype
201      * @param expected a class object representing the desired result type {@code T}
202      * @param lookup the lookup object that created this MethodHandleInfo, or one with equivalent access privileges
203      * @return a reference to the method, constructor, or field object
204      * @throws    ClassCastException if the member is not of the expected type
205      * @throws    NullPointerException if either argument is {@code null}
206      * @throws    IllegalArgumentException if the underlying member is not accessible to the given lookup object
207      */
208     public <T extends Member> T reflectAs(Class<T> expected, Lookup lookup);
209 
210     /**
211      * Returns the access modifiers of the underlying member.
212      * @return the Java language modifiers for underlying member,
213      *         or -1 if the member cannot be accessed
214      * @see Modifier
215      * @see #reflectAs
216      */
217     public int getModifiers();
218 
219     /**
220      * Determines if the underlying member was a variable arity method or constructor.
221      * Such members are represented by method handles that are varargs collectors.
222      * @implSpec
223      * This produces a result equivalent to:
224      * <pre>{@code
225      *     getReferenceKind() >= REF_invokeVirtual && Modifier.isTransient(getModifiers())
226      * }</pre>
227      *
228      *
229      * @return {@code true} if and only if the underlying member was declared with variable arity.
230      */
231     // spelling derived from java.lang.reflect.Executable, not MethodHandle.isVarargsCollector
232     public default boolean isVarArgs()  {
233         // fields are never varargs:
234         if (MethodHandleNatives.refKindIsField((byte) getReferenceKind()))
235             return false;
236         // not in the public API: Modifier.VARARGS
237         final int ACC_VARARGS = 0x00000080;  // from JVMS 4.6 (Table 4.20)
238         assert(ACC_VARARGS == Modifier.TRANSIENT);
239         return Modifier.isTransient(getModifiers());
240     }
241 
242     /**
243      * Returns the descriptive name of the given reference kind,
244      * as defined in the <a href="MethodHandleInfo.html#refkinds">table above</a>.
245      * The conventional prefix "REF_" is omitted.
246      * @param referenceKind an integer code for a kind of reference used to access a class member
247      * @return a mixed-case string such as {@code "getField"}
248      * @throws    IllegalArgumentException if the argument is not a valid
249      *            <a href="MethodHandleInfo.html#refkinds">reference kind number</a>
250      */
251     public static String referenceKindToString(int referenceKind) {
252         if (!MethodHandleNatives.refKindIsValid(referenceKind))
253             throw newIllegalArgumentException("invalid reference kind", referenceKind);
254         return MethodHandleNatives.refKindName((byte)referenceKind);
255     }
256 
257     /**
258      * Returns a string representation for a {@code MethodHandleInfo},
259      * given the four parts of its symbolic reference.
260      * This is defined to be of the form {@code "RK C.N:MT"}, where {@code RK} is the
261      * {@linkplain #referenceKindToString reference kind string} for {@code kind},
262      * {@code C} is the {@linkplain java.lang.Class#getName name} of {@code defc}
263      * {@code N} is the {@code name}, and
264      * {@code MT} is the {@code type}.
265      * These four values may be obtained from the
266      * {@linkplain #getReferenceKind reference kind},
267      * {@linkplain #getDeclaringClass declaring class},
268      * {@linkplain #getName member name},
269      * and {@linkplain #getMethodType method type}
270      * of a {@code MethodHandleInfo} object.
271      *
272      * @implSpec
273      * This produces a result equivalent to:
274      * <pre>{@code
275      *     String.format("%s %s.%s:%s", referenceKindToString(kind), defc.getName(), name, type)
276      * }</pre>
277      *
278      * @param kind the {@linkplain #getReferenceKind reference kind} part of the symbolic reference
279      * @param defc the {@linkplain #getDeclaringClass declaring class} part of the symbolic reference
280      * @param name the {@linkplain #getName member name} part of the symbolic reference
281      * @param type the {@linkplain #getMethodType method type} part of the symbolic reference
282      * @return a string of the form {@code "RK C.N:MT"}
283      * @throws    IllegalArgumentException if the first argument is not a valid
284      *            <a href="MethodHandleInfo.html#refkinds">reference kind number</a>
285      * @throws    NullPointerException if any reference argument is {@code null}
286      */
287     public static String toString(int kind, Class<?> defc, String name, MethodType type) {
288         Objects.requireNonNull(name); Objects.requireNonNull(type);
289         return String.format("%s %s.%s:%s", referenceKindToString(kind), defc.getName(), name, type);
290     }
291 }
--- EOF ---