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) {
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.

Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

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


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 ( <->    
2. mismatched type with same semantic attribute
   (A.type(int) <-> B.type(string))
3. 1 to n mapping ( <-> 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.             sprintf(B.title, "%s", $1);,A.month,A.year:       sprintf(, "%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, 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 =, $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 <>, 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:
2. use Runtime.exec("javac") to compiler it
3. use Class.forName("...mycode") to get the instance of your class
4. call the method of your class


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.