下面列出了java.lang.invoke.MethodHandles#lookup ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
h = l.findVirtual(LambdaReceiver_A.class, "f", mt(int.class));
MethodType X = mt(int.class, LambdaReceiver.class);
MethodType A = mt(int.class, LambdaReceiver_A.class);
MethodType mti = mt(IA.class);
CallSite cs = LambdaMetafactory.metafactory(l, "m", mti,A,h,X);
IA p = (IA)cs.dynamicInvoker().invoke();
LambdaReceiver_A lra = new LambdaReceiver_A();
try {
p.m(lra);
} catch (ClassCastException cce) {
return;
}
throw new AssertionError("CCE expected");
}
@Test
public void testReturnOnStack() throws Throwable {
MethodHandles.Lookup l = MethodHandles.lookup();
MethodHandle consumeIdentity = l.findStatic(
PermuteArgsReturnVoidTest.class, "consumeIdentity",
MethodType.methodType(String.class, String.class, int.class, int.class));
MethodHandle consumeVoid = l.findStatic(
PermuteArgsReturnVoidTest.class, "consumeVoid",
MethodType.methodType(void.class, String.class, int.class, int.class));
MethodHandle f = MethodHandles.foldArguments(consumeIdentity, consumeVoid);
MethodHandle p = MethodHandles.permuteArguments(f, MethodType.methodType(String.class, String.class, int.class, int.class), 0, 2, 1);
String s = (String) p.invoke("IN", 0, 0);
Assert.assertEquals(s.getClass(), String.class);
Assert.assertEquals(s, "IN");
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
h = l.findVirtual(LambdaReceiver_A.class, "f", mt(int.class));
MethodType X = mt(int.class, LambdaReceiver.class);
MethodType A = mt(int.class, LambdaReceiver_A.class);
MethodType mti = mt(IA.class);
CallSite cs = LambdaMetafactory.metafactory(l, "m", mti,A,h,X);
IA p = (IA)cs.dynamicInvoker().invoke();
LambdaReceiver_A lra = new LambdaReceiver_A();
try {
p.m(lra);
} catch (ClassCastException cce) {
return;
}
throw new AssertionError("CCE expected");
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
h = l.findVirtual(LambdaReceiver_A.class, "f", mt(int.class));
MethodType X = mt(int.class, LambdaReceiverBridge.class);
MethodType A = mt(int.class, LambdaReceiver_A.class);
MethodType mti = mt(IA.class);
CallSite cs = LambdaMetafactory.altMetafactory(l, "m", mti,X,h,X,
LambdaMetafactory.FLAG_BRIDGES, 1, A);
IA p = (IA)cs.dynamicInvoker().invoke();
LambdaReceiver_A lra = new LambdaReceiver_A();
try {
p.m(lra);
} catch (ClassCastException cce) {
return;
}
throw new AssertionError("CCE expected");
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
h = l.findVirtual(LambdaReceiver_A.class, "f", mt(int.class));
MethodType X = mt(int.class, LambdaReceiver.class);
MethodType A = mt(int.class, LambdaReceiver_A.class);
MethodType mti = mt(IA.class);
CallSite cs = LambdaMetafactory.metafactory(l, "m", mti,A,h,X);
IA p = (IA)cs.dynamicInvoker().invoke();
LambdaReceiver_A lra = new LambdaReceiver_A();
try {
p.m(lra);
} catch (ClassCastException cce) {
return;
}
throw new AssertionError("CCE expected");
}
/**
* Hop from unnamed to named module.
*
* [A0] retains PUBLIC access
*/
public void testFromUnnamedToNamedModule() throws Exception {
Lookup lookup = MethodHandles.lookup();
lookup = MethodHandles.privateLookupIn(unnamedClass, lookup).in(p1_Type1);
assertTrue(lookup.lookupModes() == PUBLIC); // A0
// m1
findConstructor(lookup, p1_Type1, void.class);
findConstructorExpectingIAE(lookup, p2_Type2, void.class);
// m2
findConstructor(lookup, q1_Type1, void.class);
findConstructorExpectingIAE(lookup, q2_Type2, void.class);
// java.base
findConstructor(lookup, Object.class, void.class);
findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
// unnamed
findConstructor(lookup, unnamedClass, void.class);
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
h = l.findVirtual(LambdaReceiver_A.class, "f", mt(int.class));
MethodType X = mt(int.class, LambdaReceiver.class);
MethodType A = mt(int.class, LambdaReceiver_A.class);
MethodType mti = mt(IA.class);
CallSite cs = LambdaMetafactory.metafactory(l, "m", mti,A,h,X);
IA p = (IA)cs.dynamicInvoker().invoke();
LambdaReceiver_A lra = new LambdaReceiver_A();
try {
p.m(lra);
} catch (ClassCastException cce) {
return;
}
throw new AssertionError("CCE expected");
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
MethodHandle hV = l.findStatic(LambdaReturn.class, "hereV", mt(void.class));
MethodHandle hS = l.findStatic(LambdaReturn.class, "hereS", mt(String.class));
List<String> errs = new ArrayList<>();
MethodType V = mt(void.class);
MethodType S = mt(String.class);
MethodType O = mt(Object.class);
MethodType I = mt(int.class);
amf(errs, hS, S, S, O, true);
amf(errs, hS, S, S, V, false);
amf(errs, hS, S, S, I, false);
amf(errs, hS, O, S, S, true);
amf(errs, hS, V, S, S, false);
amf(errs, hS, I, S, S, false);
amf(errs, hS, O, O, S, false);
amf(errs, hS, S, O, O, false);
amf(errs, hV, V, V, O, false);
amf(errs, hV, V, V, I, false);
amf(errs, hV, V, V, S, false);
amf(errs, hV, O, V, V, false);
amf(errs, hV, I, V, V, false);
amf(errs, hV, S, V, V, false);
if (errs.size() > 0) {
for (String err : errs) {
System.err.println(err);
}
throw new AssertionError("Errors: " + errs.size());
}
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
MethodHandle hV = l.findStatic(LambdaReturn.class, "hereV", mt(void.class));
MethodHandle hS = l.findStatic(LambdaReturn.class, "hereS", mt(String.class));
List<String> errs = new ArrayList<>();
MethodType V = mt(void.class);
MethodType S = mt(String.class);
MethodType O = mt(Object.class);
MethodType I = mt(int.class);
amf(errs, hS, S, S, O, true);
amf(errs, hS, S, S, V, false);
amf(errs, hS, S, S, I, false);
amf(errs, hS, O, S, S, true);
amf(errs, hS, V, S, S, false);
amf(errs, hS, I, S, S, false);
amf(errs, hS, O, O, S, false);
amf(errs, hS, S, O, O, false);
amf(errs, hV, V, V, O, false);
amf(errs, hV, V, V, I, false);
amf(errs, hV, V, V, S, false);
amf(errs, hV, O, V, V, false);
amf(errs, hV, I, V, V, false);
amf(errs, hV, S, V, V, false);
if (errs.size() > 0) {
for (String err : errs) {
System.err.println(err);
}
throw new AssertionError("Errors: " + errs.size());
}
}
public void test() throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodType mt = MethodType.methodType(void.class);
try {
Class<?> checkInittedHolder = TestPrivateMemberPackageSibling.class;
// Original model: checkInittedHolder = Class.class;
// Not using Class.checkInitted because it could change without notice.
MethodHandle mh = lookup.findStatic(checkInittedHolder, "checkInitted", mt);
throw new RuntimeException("IllegalAccessException not thrown");
} catch (IllegalAccessException e) {
// okay
System.out.println("Expected exception: " + e.getMessage());
}
}
public static void main(String[] args) throws Throwable {
MethodHandles.Lookup ll = MethodHandles.lookup();
h = ll.findStatic(T8032704.class, "here", mt(void.class));
if (mf(ll)) throw new AssertionError("Error: Should work");
if (!mf(MethodHandles.publicLookup())) throw new AssertionError("Error: Should fail - public");
if (!mf(ll.in(T8032704other.class))) throw new AssertionError("Error: Should fail - other");
if (!mf(ll.in(Thread.class))) throw new AssertionError("Error: Should fail - Thread");
}
private static MethodHandle initRegisterShutdownHookMethodHandle() {
final MethodHandles.Lookup lookup = MethodHandles.lookup();
try {
final Class<?> javaLangAccessClazz = findJavaLangAccessClass(lookup);
return findRegisterShutdownHookMethodHandle(lookup, javaLangAccessClazz);
} catch (Throwable t) {
logger.warn("Failed to initialized registerShutdownHook MethodHandle", t);
dumpJdkInfo();
}
return null;
}
/**
* Starting with a full power Lookup, use dropLookupMode to create new Lookups
* with reduced access.
*/
public void testReducingAccess() {
Lookup lookup = MethodHandles.lookup();
final Class<?> lc = lookup.lookupClass();
assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE|PROTECTED|PRIVATE));
lookup = lookup.dropLookupMode(PROTECTED);
assertTrue(lookup.lookupClass() == lc);
assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE|PRIVATE));
lookup = lookup.dropLookupMode(PRIVATE);
assertTrue(lookup.lookupClass() == lc);
assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE));
lookup = lookup.dropLookupMode(PACKAGE);
assertTrue(lookup.lookupClass() == lc);
assertTrue(lookup.lookupModes() == (PUBLIC|MODULE));
lookup = lookup.dropLookupMode(MODULE);
assertTrue(lookup.lookupClass() == lc);
assertTrue(lookup.lookupModes() == PUBLIC);
lookup = lookup.dropLookupMode(PUBLIC);
assertTrue(lookup.lookupClass() == lc);
assertTrue(lookup.lookupModes() == 0);
// repeat with lookup has no access
lookup = lookup.dropLookupMode(PUBLIC);
assertTrue(lookup.lookupClass() == lc);
assertTrue(lookup.lookupModes() == 0);
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
h = l.findVirtual(T8032697_A.class, "f", mt(int.class));
if (mf(mt(I.class, T8032697.class), mt(int.class))) throw new AssertionError("Error: Should work");
if (mf(mt(IA.class), mt(int.class, T8032697.class))) throw new AssertionError("Error: Should work");
if (!mf(mt(I.class, T8032697_A.class), mt(int.class))) throw new AssertionError("Error: Should fail");
if (!mf(mt(IA.class), mt(int.class, T8032697_A.class))) throw new AssertionError("Error: Should fail");
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
h = l.findStatic(T8032711.class, "here", mt(void.class));
if (mf(void.class)) throw new AssertionError("Error: Should work");
if (!mf(String.class)) throw new AssertionError("Error: Should fail");
}
@Test
@Tag("PASSING")
@Order(2)
public void methodHandlePrivateMethod() {
String expectedOutput = "[DemoClass] - Private method via Method Handles";
/*
* DONE:
* Get a non-public lookup from java.lang.invoke.MethodHandles
* Non-public methods are looked up via "lookup"
* Find the differences between lookup() and publicLookup() on MethodHandles.
* Check API: java.lang.invoke.MethodHandles.lookup()
*/
MethodHandles.Lookup privateMethodHandlesLookup = MethodHandles.lookup();
try {
/*
* DONE:
* Replace the "null"s with valid values to produce a privateMethod instance.
* Create a method instance that matches the name "privateMethod()"
* See java.lang.class for a getDeclaredMethod()
* Look for the declared method on the DemoClass.class
* The privateMethod() needs a String input parameter.
* Same call as is used in vanilla reflection.
* Check API: java.lang.Class.getDeclaredMethod(?, ?)
*/
Method privateMethod =
DemoClass.class.getDeclaredMethod("privateMethod",
String.class); // Method name, Class ... = Parameter types
/*
* Method has to be made accessible.
* Not setting this will cause IllegalAccessException
* Setting accessible to true causes the JVM to skip access control checks
*
* This is needed to access non-public content
*/
privateMethod.setAccessible(true);
/*
* DONE:
* Replace the "null" with a valid value to get an unreflected private method handle.
* Unreflect to create a method handle from a method instance
* Generate a MethodHandle from the method instance created earlier.
* See unreflect method in the innerclass Lookup of MethodHandles.
* java.lang.invoke.MethodHandles.Lookup.unreflect()
* We can unreflect the method since we bypassed the access control checks above.
* Check API: java.lang.invoke.MethodHandles.Lookup.unreflect(?)
*/
MethodHandle privateMethodHandle =
privateMethodHandlesLookup.unreflect(privateMethod);
DemoClass demoClass = new DemoClass();
assertEquals(expectedOutput,
privateMethodHandle.invoke(demoClass,
"via Method Handles"),
"Method handles invocation failed");
} catch (NoSuchMethodException | IllegalAccessException e) {
fail("Failed to execute a private method invocation via Method Handles: "
+ e.getMessage());
} catch (Throwable t) {
// invoke throws a Throwable (hence catching Throwable separately).
fail(TEST_FAILURE.getValue() + t.getMessage());
}
}
public static void main(String[] args) throws Throwable {
l = MethodHandles.lookup();
h = l.findStatic(T8032711.class, "here", mt(void.class));
if (mf(void.class)) throw new AssertionError("Error: Should work");
if (!mf(String.class)) throw new AssertionError("Error: Should fail");
}
public static MethodHandles.Lookup lookup() { return MethodHandles.lookup(); }
public static Lookup lookup() { return MethodHandles.lookup(); }