Run Piece of Code Contained in a String

Run piece of code contained in a String

As has already been suggested you can compile, save and run code on the fly using the Compiler API.

Another neat alternative would be to use beanshell. Beanshell is no longer actively developed, but I can vouch for it's reliability, I've used it successfully in multiple production projects.

Execute code from a String in Java

You can't do this as easily as I imagine you hope to. The kind of thing you're describing is something you might see in a dynamic language. Java is very much not a dynamic language - this is part of its character.

If you have tools.jar in your classpath, you can compile Java code from within your Java program:

com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
String[] options = new String[] {
"-classpath", classpath, "-d", outputDir, filename
};
javac.compile(options);

From there you could wrestle with the classloader, load the class you have compiled, and run it.

However this is not an easy or mainstream way to use Java, and generally people don't do it because it's neither good practice nor necessary. It is a security feature that you can't run code supplied by the user after compilation.


If you want a more dynamic language, in the Java ecosystem, you could look at Groovy.


Alternatively, you can run user-supplied Javascript, giving it controlled access to your Java program's data, using the Java Scripting API.

Run code from a string in Java

If the code is in JavaScript then you can run it with JavaScript engine:

Object res = new ScriptEngineManager().getEngineByName("js").eval(str);

JavaScript engine is part of Java SE since 1.6. See this guide http://download.java.net/jdk8/docs/technotes/guides/scripting/programmer_guide/index.html for details

Running a piece of C code stored in a Java String

Let me clarify your two Cases.

Case 1 refers to running a C program out of process. This is not what most people consider "invoke the native method from java". You cannot create a native field in Main. Actually, Java does not have native fields, only native methods. But in Case 1, you don't use native methods, either. You can compile and run any program, written in C or any other language (provided a compiler is available in the runtime environment). To do so, you use shell commands (Runtime.exec()) both to compile the program and to run it. Parameters for the C program can be passed 'on the command line' as specified in Runtime.exec(). It can communicate with your Java process with any IPC of your choice. Typically, we simply use a pipe to read the stdout of the child process.

Case 2 runs the native code in-process, using JNI (Java Native Interface). The flow that you describe here is correct, but you can modify it to use a shared library that is built at runtime. First of all, remove the native method and also loadLibrary() to a separate class. Make sure that the classloader loads this class only after your Main class runs the gcc -o libMain.so command (using the same Runtime.exec() as in Case 1). This way, the static constructor will load the freshly built library.

In both Cases you don't need to recompile your Java. You don't need to run javah to build libMain.so - this is a convenience step only, to guarantee that the C headers are in sync with the Java class. But in your situation, the Java class does not change - therefore the native method signature does not change, too.

Note that Case 1 is easier, especially if you must run different compiled C 'strings', but Case 2 may deliver better performance, if you must call the native method many times.

Run contents of string in java

Try BeanShell , build your app with jar library.

import bsh.Interpreter;
private void runString(String code){
Interpreter interpreter = new Interpreter();
try {
interpreter.set("context", this);//set any variable, you can refer to it directly from string
interpreter.eval(code);//execute code
}
catch (Exception e){//handle exception
e.printStackTrace();
}
}

Execute a string as a piece of HTML/javascript code

You can use eval, and yes multiple statements will be executed. BUT, it is generally a bad idea to use eval. In most cases you can probably accomplish whatever you are trying to do without eval.

eval can be quite dangerous if used with user supplied code, such as something from a form or URL. It opens you up to Cross-Site Scripting (XSS) attacks. Just avoiding it is the best course of action, as this answer mentions, sanitizing input before putting it through eval is not at all straight forward and very error prone.

A couple of other less important problems with using eval are that it makes code hard to debug and it is slow. It makes it hard if not impossible for browsers to optimize and/or cache it like they do other code.

Update

I'm surprised I neglected to mention this when I originally answered this, but explicitly using the eval statement is not the only way eval can be invoked in JavaScript. Passing code instead of a function reference to setTimeout or setInterval will implicitly eval that code.

// This evals:
setTimeout("doSomething()", 1000);
// This does not eval:
setTimeout(doSomething, 1000); // also shorter :)

Although not exactly the same as eval, the Function constructor also has similar security concerns associated with it.

let xss = 'alert("XSS")';
// whatever is in the string passed to Function// becomes the body of the functionlet doSomething = new Function(xss);
document.querySelector('button').addEventListener('click', doSomething, false);
<button>Do Something</button>

How do I execute a string containing Python code in Python?

In the example a string is executed as code using the exec function.

import sys
import StringIO

# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()

code = """
def f(x):
x = x + 1
return x

print 'This is my output.'
"""

# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr

exec code

# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

print f(4)

s = codeErr.getvalue()

print "error:\n%s\n" % s

s = codeOut.getvalue()

print "output:\n%s" % s

codeOut.close()
codeErr.close()


Related Topics



Leave a reply



Submit