0

I have a string constructed at run time like

str = "a+dataValue(i)";

where 'a' is a variable, 'dataValue(i)' is a function with argument i

Now I have a function where I want to use string str as part of code. For example

 public void func()
     {
        for(int i=0;i<n;i++)
          Sytem.out.println(converted_to_java_source(str)); //(i.e.) a+dataValue(i);  it should be converted at runtime not compile time 

     } 

I need output like as follows:

 when a = 2; dataValue(i) returns i; n = 5
 On call to func it should print
 2 3 4 5 6 7

Thank you.

1

2 Answers 2

2

You are looking for the Java equivalent of the eval function / method in dynamically typed languages like JavaScript, Perl, Python and so on. Unfortunately there isn't one.

There are various ways to do this kind of thing in Java, but they are all expensive, and come with a variety of other down-sides.

My advice is to look for another (easier / cheaper) way to meet your requirement.


If you really need to go down the eval route, then here are some related Q/A's which give a reasonable coverage of the options.:

Sign up to request clarification or add additional context in comments.

Comments

0

You could take a look at the Byte Code Engineering Libraray (BCEL) or ASM. In either case, things can get messy and overcomplicated so I would recommend what Stephen suggested and try to look for another way.

You could, for instance, use som if else statements to call your function in the usual manner, maybe something like:

String functionName = "...";
if (functionName.toLowerCase().equals("someMethodName")
{
     someMethodName(someParams);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.