JAVA实现的可以带参数的公式表达式计算

package com.codecronch.service;




import java.util.HashMap;


import org.apache.log4j.Logger;


import com.codecronch.util.time.TimerTick;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.googlecode.aviator.exception.ExpressionSyntaxErrorException;


/**
 * 公式表达式工具
 * @author 赵聪慧
 * 2013-3-8
 */
public class FormualService {
//	/**
//	 * Logger for this class
//	 */
	private static final Logger logger = Logger.getLogger(FormualService.class);


	private static FormualService instance=new FormualService();
	public static FormualService getInstance(){
		return instance;
	}
	HashMap<String, Expression> expressMap=new HashMap<String, Expression>();
	private Object lock=new Object();
	private FormualService(){
	}
	
	public void regExpress(String express) throws ExpressionSyntaxErrorException{
		synchronized (lock) {
			Expression compile = AviatorEvaluator.compile(express);
			expressMap.put(express, compile);	
		}
	}
	
	/**
	 * 
	 * @param param	参数  
	 * @param express 表达式
	 * @return
	 * @throws FormualException
	 */
	public Double execute(HashMap<String, Object> param, String express)throws FormualException {
		Expression expression = null ;
		synchronized (lock) {
			try {
				expression = expressMap.get(express);
				if (expression == null) {
					expression = AviatorEvaluator.compile(express);
					expressMap.put(express, expression);
					logger.error(express + "没有被注册过");
				}
			} catch (Exception ex) {
				logger.error(express+"解析失败",ex);
			}
		}
		if(expression ==null){
			throw new FormualException(express+"解析失败");
		}
		TimerTick createTick = TimerTick.createTick();
		Object execute = expression.execute(param);
		if(createTick.tickNow()>10){
			logger.error(express+"公式解析时间过长 请优化 耗时"+createTick.formatString());
		}
		return (Double) execute;
	}
	
	public static void main(String agrs[]){
		HashMap<String, Object> sss=new HashMap<String, Object>();
		sss.put("伙伴攻击力", 10);
		sss.put("技能等级", 1000l);
		long currentTimeMillis = System.currentTimeMillis();
		Double compile = null;
		try {
			compile = FormualService.getInstance().execute(sss, "伙伴攻击力*(1+0.3*技能等级)");
			System.out.println(compile.doubleValue());;
		} catch (FormualException e) {
			e.printStackTrace();
		}
		System.out.println(System.currentTimeMillis()-currentTimeMillis);
//		 Random r=new Random(1);
//		for (int i = 0; i < 10; i++) {
//			System.out.println(r.nextInt());
//		}
//		System.out.println("-");
//		r=new Random(1);
//		for (int i = 0; i < 10; i++) {
//			System.out.println(r.nextInt());
//		}
	}




}
class FormualException extends Exception{


	/**
	 * 
	 */
	private static final long serialVersionUID = 4885973114651657984L;


	public FormualException(String msg){
		super(msg);
	}
}

 

你可能感兴趣的:(java实现)