Java⼯具:字符串转化为表达式进⾏判断1.场景:判断某个字符串匹配未知长度List<String>字符串集合,(1.遍历。2.组装表达式)
bigdecimal转换为integer我倾向于后者
import java.math.BigDecimal;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import 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 = EngineByName("js");
engine.put("type", cla);
Object result = null;
try {
result = engine.eval(express);
} catch (ScriptException e) {
// ("字符串转化运算表达式出错", e);
e.printStackTrace();
}
return (boolean) result;
}
// 获取表达式
public static String getExpress(List<Class> 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, (0)));
String();
}
for (int i = 0; i < listStr.size(); i++) {
if (i == 0) {
str.append(String.format(modelStart, (i)));
continue;
}
if (i == listStr.size() - 1) {
str.append(String.format(modelEnd, (i)));
continue;
}
str.append(String.format(modelMid, (i)));
}
String();
}
public static List<Class> classLists(){
List<Class> list = wArrayList();
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;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。