问题描述
我正在开发一个程序,我希望用户定义一个简单的函数,例如 randomInt(0,10)
或者 randomString(10)
而不是静态参数.解析和处理此类功能的最佳方法是什么?
I am working on a program, where I want users to define a simple functions like randomInt(0,10)
or randomString(10)
instead of static arguments. What is the best way to parse and process such functions ?
我还没有发现任何此类问题的示例,解析器不必具有超高效率,它不会经常被调用,但主要是我想着重于良好的代码可读性和可伸缩性.
I have not found any examples of such problem, the parser does not have to be ultra-efficient, it will not be called often, but mainly I want to focus on good code readability and scalability.
用户输入示例:
"This is user randomString(5) and he is randomInt(18,60) years old!"
预期输出:
"This is user phiob and he is 45 years old!"
"This is user sdfrt and he is 30 years old!"
推荐答案
一种选择是使用Spring SPEL.但这会迫使您稍微改变一下表达式并使用Spring库:
One option is to use Spring SPEL. But it forces you to change the expression a little and use Spring library:
表达式可以如下所示:
'This is user ' + randomString(5) + ' and he is ' + randomInt(18,60) + ' years old!'
或者这个:
This is user #{randomString(5)} and he is #{randomInt(18,60)} years old!
或者您可以通过自定义TemplateParserContext
来实现自己的功能.
or you can implement your own by having a custom TemplateParserContext
.
这是代码:
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class SomeTest {
@Test
public void test() {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(
"This is user #{randomString(5)} and he is #{randomInt(18,60)} years old!",
new TemplateParserContext() );
//alternative
//Expression exp = parser.parseExpression(
// "'This is user ' + randomString(5) + ' and he is ' + randomInt(18,60) + ' years old!'");
// String message = (String) exp.getValue( new StandardEvaluationContext(this) );
String message = (String) exp.getValue( new StandardEvaluationContext(this) );
}
public String randomString(int i) {
return "rs-" + i;
}
public String randomInt(int i, int j) {
return "ri-" + i + ":" + "j";
}
}
无论传递给StandardEvaluationContext
的任何对象都应具有这些方法.我将它们放在也运行表达式的同一个类中.
Whatever object you pass to StandardEvaluationContext
should have those methods. I put them in the same class that also runs the expression.
这篇关于Java-解析用户定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!