简体   繁体   中英

Evaluate a string like Java code

In Java I have a method:

private boolean testFunction(int x){

   // codes goes here..
}

Now I have a expression written in file something like:

if(testFunction(10)){ return "ok"; }else{ return null;}

I am storing this in a String variable inside java program and want to execute it like it should execute as Java code:

if(testFunction(10)){ return "ok"; }else{ return null;}`

Is it possible?

The thing is I have a web application where there are 10+ different kind of form having different kind of fields ie in some form X,Y,Z is there and X,Y is required....in some form A,B,C is there and C is only required like this.

So instead of writing validation code for each form i wanted to write a expression in XML file and at the time evaluation these expression will execute by single java method and return some value. So in this way I will just have to write expression in XML file.

No. Java is a compiled language, it is not interpreted.

There are ways of generating bytecode dynamically in Java, but they are highly involved, and aren't anywhere close to the concept of eval(String code)

If you want dynamic validation for form entries, I'd suggest using RegExp expressions which can be evaluated and matched against form input at runtime.

Unfortunately your OP was a bit vague as to what you're actually trying to achieve.

To get you started: RegExp Pattern class

If you are looking something like

public class Test {

    public static void main(String[] args) {
        Test test = new Test();
        System.out.println(test.getReturnValue(10));
        System.out.println(test.getReturnValue(11));
    }

    private boolean testFunction(int x){
        if(x == 10)
            return true;
        else
            return false;
    }

    private Object getReturnValue(int x){
        if(testFunction(x)){
            return "ok";
        }else{
            return null;
        }
    }
}

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