• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 638
  • Last Modified:

Convert string into Java statement to execute.

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) {
1 Solution
dongwonAuthor Commented:
Edited text of question

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

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

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

dongwonAuthor Commented:
Adjusted points to 150
dongwonAuthor Commented:
Adjusted points to 200

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,


dongwonAuthor Commented:

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


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.



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


dongwonAuthor Commented:

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.


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.

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.

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.


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

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now