Java工具:字符串转化为表达式进行判断

1.场景:判断某个字符串匹配未知长度List字符串集合,(1.遍历。2.组装表达式)

         我倾向于后者

package com.zycfc.mpc.process.util;
import java.math.BigDecimal;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.assertj.core.util.Lists;
public class ExpressUtils {
	public static void main(String[] args) {		
		String express = getExpress(classLists());
		System.out.println(express);
		System.out.println(judge(express, Integer.class));
	}
	// 表达式和某字符串比较
	public static boolean judge(String express, Class cla) {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		engine.put("type", cla);
		Object result = null;
		try {
			result = engine.eval(express);
		} catch (ScriptException e) {
			// log.error("字符串转化运算表达式出错", e);
			e.printStackTrace();
		}
		return (boolean) result;
	}
	// 获取表达式
	public static String getExpress(List listStr) {
		StringBuffer str = new StringBuffer();
		String modelOnly = "(type==\"%s\")";
		String modelStart = "((type==\"%s\")";
		String modelMid = "||(type==\"%s\")";
		String modelEnd = "||(type==\"%s\"))";
		if (listStr.size() == 1) {
			str.append(String.format(modelOnly, listStr.get(0)));
			return str.toString();
		}
		for (int i = 0; i < listStr.size(); i++) {
			if (i == 0) {
				str.append(String.format(modelStart, listStr.get(i)));
				continue;
			}
			if (i == listStr.size() - 1) {
				str.append(String.format(modelEnd, listStr.get(i)));
				continue;
			}
			str.append(String.format(modelMid, listStr.get(i)));
		}
		return str.toString();
	}
	public static List classLists(){
		List list = Lists.newArrayList();
		list.add(int.class);
		list.add(Integer.class);
		list.add(byte.class);
		list.add(Byte.class);
		list.add(short.class);
		list.add(Short.class);
		list.add(long.class);
		list.add(Long.class);
		list.add(char.class);
		list.add(Character.class);
		list.add(double.class);
		list.add(Double.class);
		list.add(float.class);
		list.add(Float.class);
		list.add(boolean.class);
		list.add(Boolean.class);
		list.add(String.class);
		list.add(BigDecimal.class);
		return list;
	}
}

 

你可能感兴趣的:(工具类)