114
115 /**
116 * This reflected$lookup method is the alternate implementation of
117 * the lookup method when being invoked by reflection.
118 */
119 @CallerSensitive
120 private static Lookup reflected$lookup() {
121 Class<?> caller = Reflection.getCallerClass();
122 if (caller.getClassLoader() == null) {
123 throw newIllegalArgumentException("illegal lookupClass: "+caller);
124 }
125 return new Lookup(caller);
126 }
127
128 /**
129 * Returns a {@link Lookup lookup object} which is trusted minimally.
130 * The lookup has the {@code PUBLIC} and {@code UNCONDITIONAL} modes.
131 * It can only be used to create method handles to public members of
132 * public classes in packages that are exported unconditionally.
133 * <p>
134 * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
135 * of this lookup object will be {@link java.lang.Object}.
136 *
137 * @apiNote The use of Object is conventional, and because the lookup modes are
138 * limited, there is no special access provided to the internals of Object, its package
139 * or its module. Consequently, the lookup context of this lookup object will be the
140 * bootstrap class loader, which means it cannot find user classes.
141 *
142 * <p style="font-size:smaller;">
143 * <em>Discussion:</em>
144 * The lookup class can be changed to any other class {@code C} using an expression of the form
145 * {@link Lookup#in publicLookup().in(C.class)}.
146 * but may change the lookup context by virtue of changing the class loader.
147 * A public lookup object is always subject to
148 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
149 * Also, it cannot access
150 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
151 * @return a lookup object which is trusted minimally
152 *
153 * @revised 9
154 * @spec JPMS
242 */
243 public static <T extends Member> T
244 reflectAs(Class<T> expected, MethodHandle target) {
245 SecurityManager smgr = System.getSecurityManager();
246 if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION);
247 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup
248 return lookup.revealDirect(target).reflectAs(expected, lookup);
249 }
250 // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
251 private static final java.security.Permission ACCESS_PERMISSION =
252 new ReflectPermission("suppressAccessChecks");
253
254 /**
255 * A <em>lookup object</em> is a factory for creating method handles,
256 * when the creation requires access checking.
257 * Method handles do not perform
258 * access checks when they are called, but rather when they are created.
259 * Therefore, method handle access
260 * restrictions must be enforced when a method handle is created.
261 * The caller class against which those restrictions are enforced
262 * is known as the {@linkplain #lookupClass lookup class}.
263 * <p>
264 * A lookup class which needs to create method handles will call
265 * {@link MethodHandles#lookup MethodHandles.lookup} to create a factory for itself.
266 * When the {@code Lookup} factory object is created, the identity of the lookup class is
267 * determined, and securely stored in the {@code Lookup} object.
268 * The lookup class (or its delegates) may then use factory methods
269 * on the {@code Lookup} object to create method handles for access-checked members.
270 * This includes all methods, constructors, and fields which are allowed to the lookup class,
271 * even private ones.
272 *
273 * <h1><a id="lookups"></a>Lookup Factory Methods</h1>
274 * The factory methods on a {@code Lookup} object correspond to all major
275 * use cases for methods, constructors, and fields.
276 * Each method handle created by a factory method is the functional
277 * equivalent of a particular <em>bytecode behavior</em>.
278 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
279 * Here is a summary of the correspondence between these factory methods and
280 * the behavior of the resulting method handles:
281 * <table class="striped">
282 * <caption style="display:none">lookup method behaviors</caption>
283 * <thead>
284 * <tr>
285 * <th scope="col"><a id="equiv"></a>lookup expression</th>
759
760 /** Embody the current class (the lookupClass) as a lookup class
761 * for method handle creation.
762 * Must be called by from a method in this package,
763 * which in turn is called by a method not in this package.
764 */
765 Lookup(Class<?> lookupClass) {
766 this(lookupClass, FULL_POWER_MODES);
767 // make sure we haven't accidentally picked up a privileged class:
768 checkUnprivilegedlookupClass(lookupClass);
769 }
770
771 private Lookup(Class<?> lookupClass, int allowedModes) {
772 this.lookupClass = lookupClass;
773 this.allowedModes = allowedModes;
774 }
775
776 /**
777 * Creates a lookup on the specified new lookup class.
778 * The resulting object will report the specified
779 * class as its own {@link #lookupClass lookupClass}.
780 * <p>
781 * However, the resulting {@code Lookup} object is guaranteed
782 * to have no more access capabilities than the original.
783 * In particular, access capabilities can be lost as follows:<ul>
784 * <li>If the old lookup class is in a {@link Module#isNamed() named} module, and
785 * the new lookup class is in a different module {@code M}, then no members, not
786 * even public members in {@code M}'s exported packages, will be accessible.
787 * The exception to this is when this lookup is {@link #publicLookup()
788 * publicLookup}, in which case {@code PUBLIC} access is not lost.
789 * <li>If the old lookup class is in an unnamed module, and the new lookup class
790 * is a different module then {@link #MODULE MODULE} access is lost.
791 * <li>If the new lookup class differs from the old one then {@code UNCONDITIONAL} is lost.
792 * <li>If the new lookup class is in a different package
793 * than the old one, protected and default (package) members will not be accessible.
794 * <li>If the new lookup class is not within the same package member
795 * as the old one, private members will not be accessible, and protected members
796 * will not be accessible by virtue of inheritance.
797 * (Protected members may continue to be accessible because of package sharing.)
798 * <li>If the new lookup class is not accessible to the old lookup class,
799 * then no members, not even public members, will be accessible.
4585 * </ol>
4586 * <p>
4587 * <em>Step 3: Fill in omitted functions.</em><ol type="a">
4588 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
4589 * type.
4590 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
4591 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
4592 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
4593 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
4594 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.)
4595 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
4596 * loop return type.
4597 * </ol>
4598 * <p>
4599 * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
4600 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
4601 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
4602 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
4603 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
4604 * pad out the end of the list.
4605 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch dropping unused trailing arguments}.
4606 * </ol>
4607 * <p>
4608 * <em>Final observations.</em><ol type="a">
4609 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
4610 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
4611 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
4612 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
4613 * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
4614 * <li>Each pair of init and step functions agrees in their return type {@code V}.
4615 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
4616 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
4617 * </ol>
4618 * <p>
4619 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
4620 * <ul>
4621 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
4622 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
4623 * (Only one {@code Pn} has to be non-{@code null}.)
4624 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
4625 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
4680 * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
4681 * <blockquote><pre>{@code
4682 * V... init...(A...);
4683 * boolean pred...(V..., A...);
4684 * V... step...(V..., A...);
4685 * R fini...(V..., A...);
4686 * R loop(A... a) {
4687 * V... v... = init...(a...);
4688 * for (;;) {
4689 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
4690 * v = s(v..., a...);
4691 * if (!p(v..., a...)) {
4692 * return f(v..., a...);
4693 * }
4694 * }
4695 * }
4696 * }
4697 * }</pre></blockquote>
4698 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
4699 * to their full length, even though individual clause functions may neglect to take them all.
4700 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch}.
4701 *
4702 * @apiNote Example:
4703 * <blockquote><pre>{@code
4704 * // iterative implementation of the factorial function as a loop handle
4705 * static int one(int k) { return 1; }
4706 * static int inc(int i, int acc, int k) { return i + 1; }
4707 * static int mult(int i, int acc, int k) { return i * acc; }
4708 * static boolean pred(int i, int acc, int k) { return i < k; }
4709 * static int fin(int i, int acc, int k) { return acc; }
4710 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4711 * // null initializer for counter, should initialize to 0
4712 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4713 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4714 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4715 * assertEquals(120, loop.invoke(5));
4716 * }</pre></blockquote>
4717 * The same example, dropping arguments and using combinators:
4718 * <blockquote><pre>{@code
4719 * // simplified implementation of the factorial function as a loop handle
4720 * static int inc(int i) { return i + 1; } // drop acc, k
|
114
115 /**
116 * This reflected$lookup method is the alternate implementation of
117 * the lookup method when being invoked by reflection.
118 */
119 @CallerSensitive
120 private static Lookup reflected$lookup() {
121 Class<?> caller = Reflection.getCallerClass();
122 if (caller.getClassLoader() == null) {
123 throw newIllegalArgumentException("illegal lookupClass: "+caller);
124 }
125 return new Lookup(caller);
126 }
127
128 /**
129 * Returns a {@link Lookup lookup object} which is trusted minimally.
130 * The lookup has the {@code PUBLIC} and {@code UNCONDITIONAL} modes.
131 * It can only be used to create method handles to public members of
132 * public classes in packages that are exported unconditionally.
133 * <p>
134 * As a matter of pure convention, the {@linkplain Lookup#lookupClass() lookup class}
135 * of this lookup object will be {@link java.lang.Object}.
136 *
137 * @apiNote The use of Object is conventional, and because the lookup modes are
138 * limited, there is no special access provided to the internals of Object, its package
139 * or its module. Consequently, the lookup context of this lookup object will be the
140 * bootstrap class loader, which means it cannot find user classes.
141 *
142 * <p style="font-size:smaller;">
143 * <em>Discussion:</em>
144 * The lookup class can be changed to any other class {@code C} using an expression of the form
145 * {@link Lookup#in publicLookup().in(C.class)}.
146 * but may change the lookup context by virtue of changing the class loader.
147 * A public lookup object is always subject to
148 * <a href="MethodHandles.Lookup.html#secmgr">security manager checks</a>.
149 * Also, it cannot access
150 * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
151 * @return a lookup object which is trusted minimally
152 *
153 * @revised 9
154 * @spec JPMS
242 */
243 public static <T extends Member> T
244 reflectAs(Class<T> expected, MethodHandle target) {
245 SecurityManager smgr = System.getSecurityManager();
246 if (smgr != null) smgr.checkPermission(ACCESS_PERMISSION);
247 Lookup lookup = Lookup.IMPL_LOOKUP; // use maximally privileged lookup
248 return lookup.revealDirect(target).reflectAs(expected, lookup);
249 }
250 // Copied from AccessibleObject, as used by Method.setAccessible, etc.:
251 private static final java.security.Permission ACCESS_PERMISSION =
252 new ReflectPermission("suppressAccessChecks");
253
254 /**
255 * A <em>lookup object</em> is a factory for creating method handles,
256 * when the creation requires access checking.
257 * Method handles do not perform
258 * access checks when they are called, but rather when they are created.
259 * Therefore, method handle access
260 * restrictions must be enforced when a method handle is created.
261 * The caller class against which those restrictions are enforced
262 * is known as the {@linkplain #lookupClass() lookup class}.
263 * <p>
264 * A lookup class which needs to create method handles will call
265 * {@link MethodHandles#lookup() MethodHandles.lookup} to create a factory for itself.
266 * When the {@code Lookup} factory object is created, the identity of the lookup class is
267 * determined, and securely stored in the {@code Lookup} object.
268 * The lookup class (or its delegates) may then use factory methods
269 * on the {@code Lookup} object to create method handles for access-checked members.
270 * This includes all methods, constructors, and fields which are allowed to the lookup class,
271 * even private ones.
272 *
273 * <h1><a id="lookups"></a>Lookup Factory Methods</h1>
274 * The factory methods on a {@code Lookup} object correspond to all major
275 * use cases for methods, constructors, and fields.
276 * Each method handle created by a factory method is the functional
277 * equivalent of a particular <em>bytecode behavior</em>.
278 * (Bytecode behaviors are described in section 5.4.3.5 of the Java Virtual Machine Specification.)
279 * Here is a summary of the correspondence between these factory methods and
280 * the behavior of the resulting method handles:
281 * <table class="striped">
282 * <caption style="display:none">lookup method behaviors</caption>
283 * <thead>
284 * <tr>
285 * <th scope="col"><a id="equiv"></a>lookup expression</th>
759
760 /** Embody the current class (the lookupClass) as a lookup class
761 * for method handle creation.
762 * Must be called by from a method in this package,
763 * which in turn is called by a method not in this package.
764 */
765 Lookup(Class<?> lookupClass) {
766 this(lookupClass, FULL_POWER_MODES);
767 // make sure we haven't accidentally picked up a privileged class:
768 checkUnprivilegedlookupClass(lookupClass);
769 }
770
771 private Lookup(Class<?> lookupClass, int allowedModes) {
772 this.lookupClass = lookupClass;
773 this.allowedModes = allowedModes;
774 }
775
776 /**
777 * Creates a lookup on the specified new lookup class.
778 * The resulting object will report the specified
779 * class as its own {@link #lookupClass() lookupClass}.
780 * <p>
781 * However, the resulting {@code Lookup} object is guaranteed
782 * to have no more access capabilities than the original.
783 * In particular, access capabilities can be lost as follows:<ul>
784 * <li>If the old lookup class is in a {@link Module#isNamed() named} module, and
785 * the new lookup class is in a different module {@code M}, then no members, not
786 * even public members in {@code M}'s exported packages, will be accessible.
787 * The exception to this is when this lookup is {@link #publicLookup()
788 * publicLookup}, in which case {@code PUBLIC} access is not lost.
789 * <li>If the old lookup class is in an unnamed module, and the new lookup class
790 * is a different module then {@link #MODULE MODULE} access is lost.
791 * <li>If the new lookup class differs from the old one then {@code UNCONDITIONAL} is lost.
792 * <li>If the new lookup class is in a different package
793 * than the old one, protected and default (package) members will not be accessible.
794 * <li>If the new lookup class is not within the same package member
795 * as the old one, private members will not be accessible, and protected members
796 * will not be accessible by virtue of inheritance.
797 * (Protected members may continue to be accessible because of package sharing.)
798 * <li>If the new lookup class is not accessible to the old lookup class,
799 * then no members, not even public members, will be accessible.
4585 * </ol>
4586 * <p>
4587 * <em>Step 3: Fill in omitted functions.</em><ol type="a">
4588 * <li>If an init function is omitted, use a {@linkplain #empty default value} for the clause's iteration variable
4589 * type.
4590 * <li>If a step function is omitted, use an {@linkplain #identity identity function} of the clause's iteration
4591 * variable type; insert dropped argument parameters before the identity function parameter for the non-{@code void}
4592 * iteration variables of preceding clauses. (This will turn the loop variable into a local loop invariant.)
4593 * <li>If a pred function is omitted, use a constant {@code true} function. (This will keep the loop going, as far
4594 * as this clause is concerned. Note that in such cases the corresponding fini function is unreachable.)
4595 * <li>If a fini function is omitted, use a {@linkplain #empty default value} for the
4596 * loop return type.
4597 * </ol>
4598 * <p>
4599 * <em>Step 4: Fill in missing parameter types.</em><ol type="a">
4600 * <li>At this point, every init function parameter list is effectively identical to the external parameter list {@code (A...)},
4601 * but some lists may be shorter. For every init function with a short parameter list, pad out the end of the list.
4602 * <li>At this point, every non-init function parameter list is effectively identical to the internal parameter
4603 * list {@code (V... A...)}, but some lists may be shorter. For every non-init function with a short parameter list,
4604 * pad out the end of the list.
4605 * <li>Argument lists are padded out by {@linkplain #dropArgumentsToMatch(MethodHandle, int, List, int) dropping unused trailing arguments}.
4606 * </ol>
4607 * <p>
4608 * <em>Final observations.</em><ol type="a">
4609 * <li>After these steps, all clauses have been adjusted by supplying omitted functions and arguments.
4610 * <li>All init functions have a common parameter type list {@code (A...)}, which the final loop handle will also have.
4611 * <li>All fini functions have a common return type {@code R}, which the final loop handle will also have.
4612 * <li>All non-init functions have a common parameter type list {@code (V... A...)}, of
4613 * (non-{@code void}) iteration variables {@code V} followed by loop parameters.
4614 * <li>Each pair of init and step functions agrees in their return type {@code V}.
4615 * <li>Each non-init function will be able to observe the current values {@code (v...)} of all iteration variables.
4616 * <li>Every function will be able to observe the incoming values {@code (a...)} of all loop parameters.
4617 * </ol>
4618 * <p>
4619 * <em>Example.</em> As a consequence of step 1A above, the {@code loop} combinator has the following property:
4620 * <ul>
4621 * <li>Given {@code N} clauses {@code Cn = {null, Sn, Pn}} with {@code n = 1..N}.
4622 * <li>Suppose predicate handles {@code Pn} are either {@code null} or have no parameters.
4623 * (Only one {@code Pn} has to be non-{@code null}.)
4624 * <li>Suppose step handles {@code Sn} have signatures {@code (B1..BX)Rn}, for some constant {@code X>=N}.
4625 * <li>Suppose {@code Q} is the count of non-void types {@code Rn}, and {@code (V1...VQ)} is the sequence of those types.
4680 * and {@code R} is the common result type of all finalizers as well as of the resulting loop.
4681 * <blockquote><pre>{@code
4682 * V... init...(A...);
4683 * boolean pred...(V..., A...);
4684 * V... step...(V..., A...);
4685 * R fini...(V..., A...);
4686 * R loop(A... a) {
4687 * V... v... = init...(a...);
4688 * for (;;) {
4689 * for ((v, p, s, f) in (v..., pred..., step..., fini...)) {
4690 * v = s(v..., a...);
4691 * if (!p(v..., a...)) {
4692 * return f(v..., a...);
4693 * }
4694 * }
4695 * }
4696 * }
4697 * }</pre></blockquote>
4698 * Note that the parameter type lists {@code (V...)} and {@code (A...)} have been expanded
4699 * to their full length, even though individual clause functions may neglect to take them all.
4700 * As noted above, missing parameters are filled in as if by {@link #dropArgumentsToMatch(MethodHandle, int, List, int)}.
4701 *
4702 * @apiNote Example:
4703 * <blockquote><pre>{@code
4704 * // iterative implementation of the factorial function as a loop handle
4705 * static int one(int k) { return 1; }
4706 * static int inc(int i, int acc, int k) { return i + 1; }
4707 * static int mult(int i, int acc, int k) { return i * acc; }
4708 * static boolean pred(int i, int acc, int k) { return i < k; }
4709 * static int fin(int i, int acc, int k) { return acc; }
4710 * // assume MH_one, MH_inc, MH_mult, MH_pred, and MH_fin are handles to the above methods
4711 * // null initializer for counter, should initialize to 0
4712 * MethodHandle[] counterClause = new MethodHandle[]{null, MH_inc};
4713 * MethodHandle[] accumulatorClause = new MethodHandle[]{MH_one, MH_mult, MH_pred, MH_fin};
4714 * MethodHandle loop = MethodHandles.loop(counterClause, accumulatorClause);
4715 * assertEquals(120, loop.invoke(5));
4716 * }</pre></blockquote>
4717 * The same example, dropping arguments and using combinators:
4718 * <blockquote><pre>{@code
4719 * // simplified implementation of the factorial function as a loop handle
4720 * static int inc(int i) { return i + 1; } // drop acc, k
|