MVEL编程式导入

Programmatic Imports for 2.0

By default, like Java, MVEL provides all java.lang.* classes pre-imported as part of the compiler and runtime. However, MVEL provides the ability to programmatically import individual classes, entire packages, and even static methods.

Taking advantage of this means taking a bit of a journey away from the cozy org.mvel.MVEL convenience class, but it's nothing too absurd.

Importing Classes

Consider the following:

// where someExpression is a String or char[] of the expression to be compiled.
 
ParserContext context = new ParserContext();
context.addImport("Message", Message.class);
context.addImport("MessageFactory", MessageFactory.class);
        
Serializable compiled = MVEL.compileExpression(someExpression, context); // compile the expresion

In this example we add two imports for both the classes Message and MessageFactory. It's important to mention, as some of you may be wondering, that it is in fact possible to alias classes here, rather than using their real names. For example:

...
context.addImport("Utils", ScriptUtilities.class);
...

In this case, the compiler will resolve the token Utils as the ScriptUtilities class. This can be handy for cases where you may be implementing a DSL on top of MVEL, and it is not your intention to expose your implementation, but rather provide an easy, short-hand API.

Importing Packages

Package imports can be accomplished through the addPackageImport method in ParserContext. Example:

ParserContext ctx = new ParserContext();
ctx.addPackageImport("java.util"); // imports the entire java.util.* package.

Serializable s = MVEL.compileExpression("map = new HashMap();", ctx);

Importing Static Methods

You can import arbitrary static methods from any Java class within the classpath so that it is accessible to the compiler, and at runtime.

ParserContext ctx = new ParserContext();
try {
    ctx.addImport("time", System.class.getMethod("currentTimeMillis", long.class)); 
}
catch (NoSuchMethodException e) {
    // handle exception here.
}

Serializable s = MVEL.compileExpression("time();" ctx);

As you may see from the example, static method imports are represented by a java.lang.reflect.Method object, so you will need to use the Reflection API to handle this. We know it's not as pretty and elegant as all the other integration code, but this really is the best way.

The more cool part of this, is that we have imported the System.currentTimeMillis() method and aliased it to the global function time() in our script. Once again, a really useful way to aggregate disparate static methods as utility functions into your scripts.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值