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.

你可能感兴趣的:(java,编程)