-1

Possible Duplicate:
Convert String to code

I need to evaluate a string containing valid Java code

eg. I should be able to get 6 from String code="Math.abs(2*3);";

Community
  • 1
  • 1

2 Answers2

1

This sounds like quite an interesting idea, can I ask what the purpose of your application will be?

The best bet is to build up a dictionary of known patterns you will support.

My first idea is that you should create an ArrayList of accepted patterns. So for example:

ArrayList<String> acceptedPatterns = new ArrayList<String>();
acceptedPatterns.add("math.abs");
acceptedPatterns.add("math.acos");

etc.

Then you can evaluate this list when you get hold of the string.

String foundPattern = null;
String myStringFromInput = editText.getText();
for (String pattern : acceptedPatterns){
  if (myStringFromInput.contains(pattern){
     // we have recognised a java method, flag this up
     foundPattern = pattern;
     break;
  }
}

At this point you would have "Math.abs" in your foundPattern variable.

You could then use your knowledge of how this method works to compute it. I can't think of a super efficient way, but a basic way that would at least get you going would be something like a big if/else statement:

int result = 0;
if (foundPattern.contains("Math.abs"){
   result = computeMathAbs(myStringFromInput);
}else if (foundPattern.contains("Math.acos"){
   // etc
}

And then in your computeMathAbs method you would do something like this:

private int computeMathAbs(String input){
   int indexOfBracket = input.indexOf("(");
   int indexOfCloseBracket = input.indexOf(")");
   String value = input.subString(indexOfBracket,indexOfCloseBracket);
   int valueInt = computeFromString(value);
   int result = Math.abs(valueInt);
   return result;
}

You could then display the result passed back.

The computeFromString() method will do a similar thing, looking for the * symbol or other symbols and turning this into a multiplication like the abs example.

Obviously this is a basic example, so you would only be able to compute one java method at a time, the complexity for more than one method at a time would be quite difficult to program I think.

You would also need to put quite a bit of error handling in, and recognise that the user might not enter perfect java. Can of worms.

biddulph.r
  • 5,226
  • 3
  • 32
  • 47
0

You can use Groovy http://groovy.codehaus.org/api/groovy/util/Eval.html

import groovy.util.Eval;

... 

    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("a", 2);
    params.put("b", 3);

    Integer res = (Integer) Eval.me("param", params, "Math.abs(param.a * param.b)");

    System.out.println("res with params = " + res);

    System.out.println("res without params = " + Eval.me("Math.abs(2*3)"));
user1516873
  • 5,060
  • 2
  • 37
  • 56