简体   繁体   中英

Coverting string to java code

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.

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.:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM