下面列出了java.lang.invoke.MethodHandles#whileLoop ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public static void testWhileLoopNoIteration() throws Throwable {
// a while loop that never executes its body because the predicate evaluates to false immediately
MethodHandle loop = MethodHandles.whileLoop(While.MH_initString, While.MH_predString, While.MH_stepString);
assertEquals(While.MT_string, loop.type());
assertEquals("a", loop.invoke());
}
@Test
public static void testWhileBadInit() throws Throwable {
boolean caught = false;
try {
While w = new While();
MethodHandle loop = MethodHandles.whileLoop(MethodHandles.empty(methodType(void.class, char.class)),
While.MH_voidPred.bindTo(w),
While.MH_voidBody.bindTo(w));
} catch (IllegalArgumentException iae) {
assertEquals("loop initializer must match: (char)void != (int)void", iae.getMessage());
caught = true;
}
assertTrue(caught);
}
@Test
public static void testWhileVoidInit() throws Throwable {
While w = new While();
int v = 5;
MethodHandle loop = MethodHandles.whileLoop(While.MH_voidInit.bindTo(w), While.MH_voidPred.bindTo(w),
While.MH_voidBody.bindTo(w));
assertEquals(While.MT_void, loop.type());
loop.invoke(v);
assertEquals(v, w.i);
}
@Test(dataProvider = "nullArgs", expectedExceptions = NullPointerException.class)
public static void testWhileNullArgs(MethodHandle pred, MethodHandle body) {
MethodHandles.whileLoop(null, pred, body);
}
@Test(dataProvider = "nullArgs", expectedExceptions = NullPointerException.class)
public static void testDoWhileNullArgs(MethodHandle body, MethodHandle pred) {
MethodHandles.whileLoop(null, body, pred);
}