`

StringExpressToBooleanLogic(Copyright)

 
阅读更多

My Dears:

亲们:

みなさん:

写这篇文章不容易,所以看到这个话,请留下您的足迹

 

今天写了一个工具,是将String型的逻辑表达式变成Boolean型的,写的很粗糙,但基本功能实现。

为什么要写这个,因为java对解释型的判断很差,所以做了这个工具的话,java也可以做解释操作了

 

嘿嘿,别的就不说了具体的下面操作:

 

package com.chenhailong.exception;

/**
 * 
 * @author chenhailong
 *下午07:30:53
 *com.chenhailong.exception
 */
public class IllegalAugmentException extends Exception{

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

	public IllegalAugmentException(Exception e) {
		super(e);
	}

}
 
package com.chenhailong.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import com.chenhailong.exception.IllegalAugmentException;

/**
 * 
 * @author chenhailong 
 * 下午07:29:51 
 * com.chenhailong.main
 */
public class StringExpressToBoolean {

	private static final String JAVASCRIPTLAN = "JavaScript";
	private static final String SUCCESS = "Success";
	private static final String FAILED = "Failed";
	private static final String FILENAME = "IFcontroller.txt";

	public static void main(String[] args) {
		try {
			String str = getStringFromFile();
			System.out.println(str);
			boolean bool = getLogic(str);
			if (bool) {
				System.out.println(SUCCESS);
			} else {
				System.out.println(FAILED);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param expressValue
	 * @return
	 * @throws IllegalAugmentException
	 * @throws ScriptException
	 */
	public static boolean getLogic(String expressValue)
			throws IllegalAugmentException, ScriptException {
		Boolean bool = null;
		if (expressValue == null || expressValue.length() == 0) {
			return false;
		}
		try {
			ScriptEngineManager mgr = new ScriptEngineManager();
			ScriptEngine engine = mgr.getEngineByName(JAVASCRIPTLAN);
			String foo = expressValue;
			bool = Boolean.valueOf(engine.eval(foo).toString());
		} catch (ScriptException e) {
			throw e;
		} catch (Exception e) {
			throw new IllegalAugmentException(e);
		}
		return bool;
	}

	/**
	 * 
	 * @return
	 * @throws IOException
	 */
	public static String getStringFromFile() throws IOException {
		String str = null;
		BufferedReader reader = new BufferedReader(new FileReader(new File(
				FILENAME)));
		while (reader.ready()) {
			str = reader.readLine();
		}
		return str;
	}

}

 代码开源,所以也没什么,希望大家努力将这个工具发扬光大,让他成为你项目中的亮点

 

嘻嘻,多多留言

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics