0

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.

4
  • 1
    Can you explain a bit why you want to do this? What problem are you solving? Commented Dec 9, 2017 at 19:19
  • If you need a java code interpreter, you could look at beanshell: beanshell.org/intro.html Commented Dec 9, 2017 at 19:20
  • Have you checked out the JShell API? Commented Dec 9, 2017 at 19:28
  • better tell us why and what you are trying to do Commented Dec 10, 2017 at 20:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.