2

Is there any way in JAVA to convert a String directly to an expression?

String s="(accountName==TESTDATA1) && (CONTAINER==bank) ||(includeInNetWorth==true)";
if(s==true){
  //I want to do something
}
assylias
  • 321,522
  • 82
  • 660
  • 783
rahul kumar
  • 43
  • 1
  • 6
  • `Boolean.parseBoolean`? – Eugene Jul 30 '18 at 12:10
  • 2
    @Eugene `parseBoolean` returns true only if you pass the string `true` (ignoring case). The OP wants to evaluate the expression. – Thiyagu Jul 30 '18 at 12:13
  • @user7 yup.. I understood that, bad sugestion – Eugene Jul 30 '18 at 12:14
  • 1
    No. Java does not provide such functionality. And you can't get local variable from their names at runtime. – zhh Jul 30 '18 at 12:17
  • @user7 though the linked answer is good, I think the OP needs those variables `accountName`, `CONTAINER` etc. from some context, not sure this would be possible – Eugene Jul 30 '18 at 12:19
  • I have gone through this link but could not find how this solution will suffice my requirement. Could u pls help in framing the code? – rahul kumar Jul 30 '18 at 12:20
  • @Eugene the accepted answer on the linked question shows how to pass values into the script engine (`engine.eval("value = 10");`). Should be possible in this example, too – Malte Hartwig Jul 30 '18 at 12:20
  • accountName,Container etc are coming to from the json file. I just want that String expression to return somehow true/false. – rahul kumar Jul 30 '18 at 12:21
  • @MalteHartwig I understand that, I am just saying if the context is big, I dont think this is going to be by any means easy – Eugene Jul 30 '18 at 12:21
  • "I just want" is not a magic sentence to make a great solution appear, you'll need some work to achieve this. – azro Jul 30 '18 at 12:23
  • 1
    @rahulkumar have you tried copying the code from the answer in the linked question and replace the conditions with yours and the `"value = 10"` by something like `"\"TESTDATA1\" = " + myJson.get("accountName")`? You need to show us some code for us to help. It would also show us why you need to evaluate the expression as a String instead of plain Java. – Malte Hartwig Jul 30 '18 at 12:25
  • If those variables are class fields you may achieve it with reflection. But if they are local variables I believe there's no way to do this. btw, why do you want to do this? – zhh Jul 30 '18 at 12:25
  • I dont think there is way to convert String to expression, however if someone can help me in splitting that string based on && and || both such that after splitting each expression can be treated as separate comparision. – rahul kumar Jul 31 '18 at 05:27
  • I guess i have got the solution how to break it. below is my code. String [] s1 = s.split("\\||&&"); for(int i=0;i – rahul kumar Jul 31 '18 at 05:44

0 Answers0