Go Premium for a chance to win a PS4. Enter to Win


Convert string into Java statement to execute.

Posted on 1997-10-17
Medium Priority
Last Modified: 2009-07-29
I'd like to know how I can convert string
containing Java statement into real Java
statement which can be executed?
Suppose I have some file which has following
condition string in prefixed format:
# file contents
condition:  "(a > b && a > c)"
Now In program,
    String strCond = "";

    // 1. Read the file and store "..."
    // part into String strCond;
    // 2. Now convert strCond into actual
    // Java statement somehow.

    // following should be equivalent to
    // if (a > b && a > c) to compiler            
    if (strCond) {
Question by:dongwon

Author Comment

ID: 1229035
Edited text of question

Expert Comment

ID: 1229036

There is no simple way to do this.  You'll need to
either parse things out using the StringTokenizer()
some kind of grammar.  

Another way would be to parse out the condition section,
then wrap things into a file:

System.out.println("if " + condition + " { \n\tdo_something();\n}");

when you save that to a file, you could compile into
a package and then load the package on the fly.  

That's about it, there's no simple way do self-modifying


Author Comment

ID: 1229037
Thanks for your answer.

I guess this is more difficult problem than I expected.

First way that you suggested is not good. Since the syntax of
condition part in file (condition : "here") accepts whole
Java syntax, if I have to manipulate StreamTokenizer() or some other lex/yacc tools, then I end up writing whole Java parser.

For second suggestion, I'm not sure what you mean by that exactly. Probably little elaboration would be appreciated.

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.


Author Comment

ID: 1229038
Adjusted points to 150

Author Comment

ID: 1229039
Adjusted points to 200

Expert Comment

ID: 1229040

If the piece after the "condition: " is always a
Java condition, then you still need to either parse
it out or write it out to a file, compile it and
then load the class to use.  

The with the first thing, if it's always a java condition
statement, you can do a subString() to eliminate the
first 11 characters so:

String newStr = conditionStr.subString(11, conditionStr.length - 1);

then, you just have to parse conditions out with the
StringTokenizer.  If, as you said, they are just Java
test statements, you just need to be able to parse out
the different comparisons and balance parens.  

Hope that helps,



Author Comment

ID: 1229041

In file, after condition, any "legal" java statement can come, not only testing statement. For instance, following can happen.

condition1: "(a > b && a > c)"
condition2: "System.out.println("..."); System.exit(0);"
condition3: "String s = tmp.subString(0, 10); while (true) doTest(s);"

In code

      if (condition1) {
      } else {

I guess as you said there is no easy to do this...


Expert Comment

ID: 1229042

Let's try a different approach.  How is this file
getting created?  Java may not be the best solution
to this problem.  We may be able to convert this file
into Java using a Perl script.  Then you can compile
the file (we can put that in the perl script too.

If that's acceptable, send me a copy of a file, and
I'll send you a script that will convert it.



Expert Comment

ID: 1229043

Oh, my e-mail is rembo@cks.com



Author Comment

ID: 1229044

First of all, I should appreciate for your help and patience.
Now let me explain the situation where I need those functionalities.

Let's suppose I have 2 systems A and B (which are distributed and
geographically remotly located). Both systems model same domain and even have exactly same data under different schema.  For instance, following is the schema:

(NOTE I'm calling this as "Meta Information")

A: name(string), day(int), month(int), year(int), type(int)
B: title(string), type(string), date(string - mm/dd/yy format)

My goal is that when system A gets a query conforming to its schema, A should translate the incoming query into another query conforming to the schema of system B and pass it on the system B.

Note that there are several obstacles:      
1. mismatched name with same semantic attribute (A.name <->    
2. mismatched type with same semantic attribute
   (A.type(int) <-> B.type(string))
3. 1 to n mapping (A.date <-> composite of

For instance, following QA should be translated into QB.

QA:     select name
        from A
        where day = 31 and month = 12 and year = 97 and
        type = 145
QB:     select title
        from B
        where date = '12/31/97' and type = 'type-145'

Another important requirements is that above "Meta Information" should not be hard-coded into system A or B. That is, those information should be written in some file and loaded into the system.

Hence, I'm thinking following file along with its ad-hoc grammar to express such translation mechanism.
# syntax       LHS:       RHS

# translation from A to B.
A.name:             sprintf(B.title, "%s", $1);
A.day,A.month,A.year:       sprintf(B.date, "%d/%d/%d", $2,$1,$3);
A.type:                  sprintf(B.type, "type-%d", $1);

# translation from A to C

Example is shown using C syntax. The meaning should be clear: LHS (for instance, A.name) will be translated using RHS function where built-in variables $1, $2, ... are to be bound to the value of variables in LHS. (for instance, in second line, $1 = A.day, $2 = A.month, $3 = A.year).

Here comes the problem. After the system loads in above file and
parse it, it should RUN the RHS part (sprintf() part) to do
translation. By modifying the above file (that is, meta information), user is able to change the translation, without touching the actual system. In some sense, the system's translation mechanism is dumb since it simply run the parsed RHS part in run-time.

This is why I asked if I could convert string into java statement (I decided Java for implementation). If you see better way for this problem (without using conversion from string to statement...), that's fine. If you use Perl to achieve same effect, that's fine too.

I hope I explained well the essence of the problem to you.



Expert Comment

ID: 1229045
Only as an alternative suggestion you and rembo might want to consider:

If you can define a set of all possible conditionals, for instance:

(a > b && a > c)
(a < b && a > c)
(a < b && a < c)

Than you can define a simple parser that determines which conditional structure was invoked and call a diffrent method for each case.

This would work arround all kinds of problems like forcing the client code to have access to a Java compiler, generating byte code manualy and class signature violations.


Expert Comment

ID: 1229046
You have described a system which requires parsing of some grammatical construct (your example is SQL), and translation according some dynamically defined meta-data. This is not conceptually too bad; however, it is not quite as easy as you had hoped in Java, since Java does not give you an easy way to compile strings.

You have a few options:
1. Use a language such as LISP, which does support compilation of strings dynamically (of course, you have to use LISP grammar, which can be a bit off-putting).

2. Use a tool like JavaCC <http://www.suntest.com/JavaCC/>, which simplifies the creation of grammars in Java. It should be at least as easy to use as yacc.

3. Define a very simple grammar, and write an ad-hoc parser.

It sounds as though the real guts of your program is the meta-data, not the parsing, so I would advise solution 2 to make it as simple as possible.  A JavaCC newsgroup is in the process if being voted, and there is already a mailing list to offer detailed help on it.

Expert Comment

ID: 1229047

Is it set up so that the first statement is the
test, the second statement is what happens if
it's true, the second if it's false?  

If so, I'll give you a script to do it.



Author Comment

ID: 1229048
Thanks for the tip, but my question was for more general one.
In fact, current approach is using JavaCC tool to specify ad hoc
language and my intention was to avoid this scheme.

Accepted Solution

Threshold earned 400 total points
ID: 1229049
If you run it in Application, not Applet, there is one way...

1. get java statement file, ie:  mycode.java
2. use Runtime.exec("javac mycode.java") to compiler it
3. use Class.forName("...mycode") to get the instance of your class
4. call the method of your class


Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This video teaches viewers about errors in exception handling.
Suggested Courses

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question