Rohit Jain
Rohit Jain

Reputation: 137

How to call a Java function which forms in String

I am using SpringBoot,

I have function in String form, I want to execute that function by passing params (so that it behaves like normal java function)

ex:

String s = "public void method_name(String name, int s) {\n" + 
                "        System.out.println(name + s);\n" + 
                "    }";

i want to call this function, input : method_name("abc" , 10)

output: abc10

I there any way or any library in JAVA??

Things i tried:

1) Used java.beans.Statement;

thanks in advance! :)

Why I need this ? I am using this function in JSON file, where i will take this function dynamically. JSON obj :

{
 "1":{
 "function" : "public void method_name(String name, int s) {\n" + 
                    "        System.out.println(name + s);\n" + 
                    "    } "
 },
 "2": {
   "function" : another function
 }
} 

Hope you understand this.

Upvotes: 0

Views: 400

Answers (1)

jqno
jqno

Reputation: 15520

This can be done: look into javax.tools.JavaCompiler.

HOWEVER

You'll be creating a HUGE security hole in your application. What if a user gains access to that json file? They'll be able to run arbitrary code on your server through your application.

You really need to ask yourself if this is something that you really want to do. Maybe there's a simpler way to achieve what you want? For example, look into the Strategy Design Pattern. Probably it can do most of what you want already.

Also, JavaCompiler is pretty difficult to get working. In addition to JavaCompiler itself, you'll need to learn about reflection and classloaders to make it work. So that's another reason not to go down this path.

Don't do it.

Upvotes: 1

Related Questions