User inputed formula parsing (eval)
Good day all,
I am trying to figure out how to allow users to call a method on some specified data.
I would like to provide a开发者_JAVA百科 predefined set of functions:
- Moving average, moving_ave(x,5) ..would be a 5 day moving average on x.
- 3*x+y....and so on...
So basically, i will provide the users with various data series (x,y,z....) and a set of functions moving_ave, + - / * ....and they should be able to write simple formulas (restricted to the functions i provide).
how can this be done?
I will be deploying this on App Engine for Java.
so for i have found out about JSR-223...but i'm not sure if its appropriate? I am thinking i can use the Eval function.
Thanks,
It sounds like what you want is an interpreter for a simple grammar. Be very wary of approaches such as that suggested by Aerosteak; allowing your user to call functions in your code directly is dangerous, and it's easy to make mistakes sandboxing it, resulting in security vulnerabilities. It'll also require you to write your own parser.
The easiest approach is probably to use an existing language - Javascript probably fits very well, and you can use Rhino, a Javascript interpreter written in Java.
You will need to use Reflection to call unknow Method. Look a Apache BeanUtil.
You can have a TextBox with the value: 1,2,3, Convert these values to Object Array.
Have another ComBo Box with all you possible Method you can call.
Then use Bean Util to call the method with the Object Array.
For Exemple:
class MyMathManager{
public void doCalculationType1(Object args...){..} public void doCalculationType2(Object args...){..} public void doCalculationType3(Object args...){..}
Then Look at the Java of BeanUtil to call these Method.
Good Luck.
This sounds like something that could probably be done on the client, rather than the server. You could write a few handy javascript functions that call a restful API on the server to provide the needed data to a few more handy javascript functions that do the useful calculations. It's almost always safe to allow users to eval on their own clients.. they can do it in any case.
精彩评论