---
title: "在Drools中使用MVEL "
author: "shift8"
date: "2013-07-30T08:56:23Z"
tags: []
categories: ["非技术"]
slug: "drools-mvel"
draft: false
lastmod: "2013-07-30T09:00:22Z"
id: 1915327
url: "https://shift8.iteye.com/blog/1915327"
---

dialect设置规则当中要使用的语言类型 ，默认除了java还有mevl。本文简单介绍mvel。   
mvel是一种嵌入式脚本语言,在规则文件上可以用这种语言建立他们的断言、返回值、Eval和推论。mvel分解析模式(Interpreted Mode)和编译模式(Compiled Mode) 

mvel语法:   
表示对象的属性 

user.name   相当于java代码 user.getName()   
user.manager.name  相当于java代码 user.getManager().getName()   
比较   
user.name == 'John Doe'   
(user.name == 'John Doe') && ((x * 2) - 1) &gt; 20 

返回值   
a = 10;   
b = (a = a * 2) + 10; 相当于java代码  a=10; a= a\*2; b=  a + 10;   
return a; 

数组和list访问:user\[5]   相当于java代码 user.get(5);   
Map访问:user\["foobar"]   相当于java代码 user.get("foobar") 

创建对象:   
new String("foo") 

对一个对象，多个属性赋值   
with (user = new User()) {   
       name = "John Doe",   
       age = 28,   
       sex = Sex.MALE,   
       admin = true   
    } 

脚本:   
note：   
语法跟一些函数语言或脚本语言差不多，如scala 

调用某些方法   
String test = "Hello";   
Object result = MVEL.eval("toUpperCase()", test); 

获取pojo的属性值   
User user = new User();   
user.setName("Bob");   
user.setPassword("Despot");   
user.setAge(30); 

String name = (String) MVEL.eval("name", user); 

比较   
public class Person {   
    private String name;   
    public void setName(String name) { this.name = name; }   
    public String getName() { return this.name; }   
} 

Person   
personInst = new Person();   
personInst.setName("Mr. Foo"); 

Object result = MVEL.eval("name == 'Mr. Foo' ", personInst); 

赋值   
Map vars = new HashMap();   
vars.put("x", new Integer(5));   
vars.put("y", new Integer(10)); 

Integer result = (Integer) MVEL.eval("x * y", vars);   
相当于java代码 Integer  result =  (Integer)vars.get("x") *  (Integer)vars.get(" y ")   
assert result.intValue() == 50;  // Mind the JDK 1.4 compatible code![](http://xinfeiyang.iteye.com/images/smiles/icon_smile.gif) 

规则文件使用mvel示例 

示例1： 

```
package com.demo.mvel 


import com.demo.* 


rule "rule1" 
dialect "mvel" 
when 
#设是规则引擎语法 
$a : Applicant( age < 18 ) 
then   
#mvel 语法 
$a.valid = false; 
end 
```

 

示例2： 

```
package com.demo.mvel 


import com.demo.* 
import java.util.List; 


rule "rule1" 
    salience 2 
     dialect "java" 
     when 
  eval(true); 
     then 
  Applicant app = new Applicant("依晨",20); 
  insert(app); 
end 


rule "rule2" 
    salience 1 
    dialect "mvel" 
    #no-loop true 不会循环 
    when 
       $app:Applicant(name == "依晨",age<30) 
    then 
       #update方法2 
      #$app.age + 1是mvel语法 
       Applicant app = new Applicant("依晨",$app.age + 1); 
       update(drools.getWorkingMemory().getFactHandleByIdentity($app),app); 
    
       #update方法1 
       #$app.setAge($app.getAge() + 1); 
       #update($app); 
       System.out.println("------" + $app.name+"("+ $app.age + ")"); 
end
```