Convert string into Java statement to execute.

Posted on 1997-10-17
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.


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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.


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



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



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 <>, 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 200 total points
ID: 1229049
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


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Java passing arguments (type error) 2 47
micro services spring boot application error 3 136
how do i compare an object based on two fields 6 48
Java DateChooser? 3 29
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

932 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now