MVEL2.0控制流

MVEL 2.0 Control Flow

MVEL's power goes beyond simple expressions. In fact, MVEL supports an assortment of control flow operators which will allow you to perform advanced scripting operations.

If-Then-Else

MVEL supports full, C/Java-style if-then-else blocks. For example:

if (var > 0) {
   System.out.println("Greater than zero!");
}
else if (var == -1) { 
   System.out.println("Minus one!");
}
else { 
   System.out.println("Something else!");
}

Ternary statements

Ternary statements are supported just as in Java:

var > 0 ? "Yes" : "No";

And nested ternary statements:

var > 0 ? "Yes" : (var == -1 ? "Minus One!" : "No")

Foreach

One of the most powerful features in MVEL is it's foreach operator. It is similar to the for each operator in Java 1.5 in both syntax and functionality. It accepts two parameters separated by a colon, the first is the local variable for the current element, and the second is the collection or array to be iterated.

For example:

count = 0;
foreach (name : people) {
   count++;
   System.out.println("Person #" + count + ":" + name);
}
    
System.out.println("Total people: " + count);

Since MVEL treats Strings as iterable objects you can iterate a String (character by character) with a foreach block:

str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

foreach (el : str) {
   System.out.print("[" + el + "]"); 
}

The above example outputs: [A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y][Z]

You can also use MVEL to count up to an integer value (from 1):

foreach (x : 9) { 
   System.out.print(x);
}

Which outputs: 123456789

Syntax Note: As of MVEL 2.0, it is now possible to simply abbreviate foreach in the same way it is in Java 5.0, by using the for keyword. For example:

for (item : collection) { ... }

For Loop

MVEL 2.0 implements standard C for-loops:

for (int i =0; i < 100; i++) { 
   System.out.println(i);
}

Do While, Do Until

do while and do until are implemented in MVEL, following the same convention as Java, with until being the inverse of while.

do { 
   x = something();
} 
while (x != null);

... is semantically equivalent to ...

do {
   x = something();
}
until (x == null);

While, Until

MVEL 2.0 implements standard while, with the addition of the inverse until.

while (isTrue()) {
   doSomething();
}

... or ...

until (isFalse()) {
   doSomething();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值