Use beanShell to parse and execute the java String method, which is similar to the eval method of javascipt.

Source: Internet
Author: User

Today, a problem occurs in the project. You need to determine the branch to be executed based on the calculation result of a String expression. The expression is dynamic. In actual implementation, only the expression is required for passing in some parameters, the expression returns a result and determines the branch of the result. There was no idea at first. After studying baidu and google, we found that beanShell can solve this problem perfectly. Therefore, I want to help students who encounter the same problem, and also serve as a record so that they will not forget it later.

First, introduce the beanshell jar package. Download URL for http://www.beanshell.org/download.html current latest version is bsh-2.0b4.jar, first create BshUtils tool class

 

Package com. freefly. utils. bsh;

Import java. util .*;

Import bsh .*;
Import org. apache. log4j .*;

/**
* <P>
* Title: BshUtils
* </P>
* <P>
* Description: beanshell tool class
* </P>
*
* @ Author fly freely
* @ Version 1.0
*/

Public final class BshUtils {
Private static Logger logger = Logger. getLogger (BshUtils. class );

Private Interpreter bsh = null;

Public BshUtils (){
Bsh = new Interpreter ();
}

Public Interpreter getBsh (){
Return bsh;
}

Public final Object eval (String expr, Map varMap) throws Exception {
Object obj = null;
If (varMap = null | null = expr | "". equals (expr )){
Return null;
}

Iterator it = varMap. keySet (). iterator ();
Try {
While (it. hasNext ()){
String key = (String) it. next ();
Object value = varMap. get (key );
SetValue (key, value );
}
Obj = bsh. eval (expr );

// Return the variable
Return obj;
}
Catch (Exception ex ){
Logger. error (ex );
Throw ex;
}
}

// Variable assignment
Private void setValue (String key, Object value) throws EvalError {
If (value instanceof Boolean ){
Bsh. set (key, (Boolean) value). booleanValue ());
} Else if (value instanceof Byte ){
Bsh. set (key, (Byte) value). byteValue ());
} Else if (value instanceof Character ){
Bsh. set (key, (Character) value). charValue ());
} Else if (value instanceof Short ){
Bsh. set (key, (Short) value). duplicate value ());
} Else if (value instanceof Integer ){
Bsh. set (key, (Integer) value). intValue ());
} Else if (value instanceof Long ){
Bsh. set (key, (Long) value). longValue ());
} Else if (value instanceof Float ){
Bsh. set (key, (Float) value). floatValue ());
} Else if (value instanceof Double ){
Bsh. set (key, (Double) value). doubleValue ());
} Else {
Bsh. set (key, value );
}
}
}
 

The next step is to call and test. Simple Support for four arithmetic operations and the built-in java methods. Whether or not the custom javabean method is supported remains to be studied.

 

 

Public class BshTest {
Public static void main (String [] args ){

BshUtils bsh = new BshUtils ();
String expr = "a = 1 & B. equals (\" c \")";
String expr2 = "a + c ";
Map <String, Object> map = new HashMap <String, Object> ();
Map. put ("a", 1 );
Map. put ("B", "c ");
Map. put ("c", 2 );
Try {
System. out. println ("-------- expr -------------->"
+ Bsh. eval (expr, map). toString ());
System. out. println ("-------- expr2 -------------->"
+ Bsh. eval (expr2, map). toString ());
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

}

}

Author's "Flying column"

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.