开发者

Converting a String Operation to Short (JAVA) [duplicate]

This question already has answers here: 开发者_StackOverflow How to evaluate a math expression given in string form? (26 answers) Closed 6 years ago.

If the string is:

String common_mpCon = "20+5*Math.ceil(2/7)"; //(equals 200 btw)

I'm trying to make the String do all the operations inside while it gets converted into a short. Is it possible? Using Short.parseShort(common_mpCon), I get an exception thrown, with googling I found no useful answer, so I finally decided to ask stackoverflow :D


If you're using Java 6, you might consider using the javax.tools.javacompiler classes. It's a lot of work, and you'd want to be very cautious about much freedom users would have to execute arbitrary code in your JVM instance.

That said, there's a great example available at http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm. It's not my code and I don't want to plagiarize, so I'll explain the technique and let you reference the link for the full example.

First, build a string containing the code you wish to call. As in actual source code, the newlines are optional.

String common_mpCon = "20+5*Math.ceil(2/7)";
String code;
code = "public class MyShortEvaluator {\n";
code += "    public static Short calculate() {\n";
code += "        return (" + common_mpCon + ");\n";
code += "    }\n";
code += "}\n";

Create a JavaFileObject which returns the value of code from its getCharContent method. Add this to an collection of JavaFileObjects, pass the result to a JavaCompiler instance's getTask() method to get a CompilationTask, and call the resulting task's call() method.

If all goes well, you can use Class.forName("MyShortEvaluator").getDeclaredMethod to get a reference to the defined class's new static method.

Of course other reflection techniques are available as well. You could define the Calculate() method in an interface, have MyShortEvaluator implement that interface, and then use newInstance to get a reference to an actual object.


java.lang.String won't do these operations for you. Believe the JVM when it tells you.

If you interpret it as JavaScript, perhaps you can pass it to the eval() method and get what you want. Try Rhino.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜