This question already has answers here:
Run piece of code contained in a String
(9 answers)
Closed 6 years ago.
Lets say i have this String: String run = "System.out.println\(\"Hello\"\)". What i want to do is run what is in the string to output Hello in console.
Maybe there is a method like String.run()?
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();
}
}
Maybe in Java 9 you could use the REPL but as it's not there yet You would need to
* create a temporary file with a class with a know to You API
* run javac on it and compile it
* load the compiled class with a class loader
* run the code
If You want to do is running dynamically defined scripts in Your code then You could use Nashorn and JavaScript. It would do what You want. Also You could use Groovy in your project instead of Java - the syntax is similar to Java but Groovy is a dynamic language.
No, you cannot do it and there's no method to run this command in String. Anything withing the double quotes becomes String literals only and compiler doesn't take care of any command written in that.
Related
This question already has answers here:
How do I parse command line arguments in Java?
(21 answers)
Closed 2 years ago.
I am coding this below functionality where I need to run a class which takes some parameters this will perform an action on the server that is given in the url ....
oracle.ucm.client.DownloadTool --ping --URL=abz.com --param1=abc --param=xyz
And this class is present in a jar which I have included in the build path.
Executing this manually through command line looks something like this:
bash$ java -classpath ".jar file location" abc.xyz.DownloadTool --ping --url=www.google.com --username=xyx --password=abc
Please let me know how to program this.
Convert your JAR file to executable. Executable name can be "ucmclient". Ref: https://coderwall.com/p/ssuaxa/how-to-make-a-jar-file-linux-executable
ucmclient oracle.ucm.client.DownloadTool --ping --URL=abz.com --param1=abc --param=xyz
In your main class:
Retrieve class name from command line arguments:
String className = args[0];
Create object of class using class name, You can use any of below option:
Use switch case
switch(className)
{
case "oracle.ucm.client.DownloadTool"
oracle.ucm.client.DownloadTool downloadTool = new oracle.ucm.client.DownloadTool();
downloadTool.main(args);
}
You can use Reflection.
You can also use factory design pattern.
This question already has answers here:
Java: Load class from string
(5 answers)
Closed 8 years ago.
Here I have found some good example:
// Prepare source somehow.
String source = "package test; public class Test { static { System.out.println(\"hello\"); } public Test() { System.out.println(\"world\"); } }";
// Save source in .java file.
File root = new File("/java"); // On Windows running on C:\, this is C:\java.
File sourceFile = new File(root, "test/Test.java");
sourceFile.getParentFile().mkdirs();
new FileWriter(sourceFile).append(source).close();
// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());
// Load and instantiate compiled class.
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".
Object instance = cls.newInstance(); // Should print "world".
System.out.println(instance); // Should print "test.Test#hashcode".
Question: Is it possible to achieve exactly the same thing without writing to a file?
#Edit:
To be more exact: I know how to compile from string (overloading JavaFileObject). But after doing this, I have no idea how to load the class. I probably missed the output-write part, but this also a thing I would like not to do.
#Edit2
For anyone interested, I created this small project to implement discussed feature: https://github.com/Krever/JIMCy
OK, so here is an example of using JavaCompiler to compile from a String input. this file is the core of it.
In this file, I load the class which is compiled. You will notice that I also detect the package and classname using regexes.
As to the output, if you want to do that in memory, it appears that you can do so if you implement your own JavaFileManager; however I have never tried that!
Note that you can debug what happens quite easily by extending ForwardingJavaFileManager
Not exactly what you are asking for, but Groovy's library for Java makes it easy to compile and evaluate expressions from String. The syntax is not identical but very similar to Java, so if you can change the strings to be compiled so they are in Groovy instead of Java, the task will be very easy. See Embedding Groovy for code samples.
I have a Ruby script that I'd like to run at the startup of my Java program.
When you tell the ScriptEngine to evaluate the code for the first time, it takes a while. I'm under the impression that the reason it takes this long is because it first needs to compile the code, right?
I found that you can compile Ruby code, and then evaluate it later. The evaluation itself is fast - the compilation part is the slow one. Here I am compiling:
jruby = new ScriptEngineManager().getEngineByName("jruby");
Compilable compilingEngine = (Compilable)jruby;
String code = "print 'HELLO!'";
CompiledScript script;
script = compilingEngine.compile(code);
This snippet is what takes a while. Later when you evaluate it, it is fine.
So of course, I was wondering if it would be possible to "save" this compiled code into a file, so in the future I can "load" it and just execute it without compiling again.
As others have said, this is not possible with CompiledScript. However, with JRuby you have another option. You can use the command line tool jrubyc to compile a Ruby script to Java bytecode like so:
jrubyc <scriptname.rb>
This will produce a class file named scriptname.class. You can run this class from the command line as if it were a normal class with a main(String[] argv) method (note: the jruby runtime needs to be in the classpath) and you can of course load it into your application at runtime.
You can find more details on the output of jrubyc here: https://github.com/jruby/jruby/wiki/JRubyCompiler#methods-in-output-class-file
According to this, no.
"Unfortunately, compiled scripts are not, by default, serializable, so they can't be pre-compiled as part of a deployment process, so compilation should be applied at runtime when you know it makes sense."
I think some really easy cache will solve your problem:
class CompiledScriptCache {
static {
CompiledScriptCache INSTANCE = new CompiledScritCache();
}
publich static CompiledScriptCache get(){
retrun INSTANCE;
};
List<CompiledScript> scripts = new ArrayList<>();
public CompiledScript get(int id){
return scripts.get(id);
}
public int add(String code){
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
Compilable compilingEngine = (Compilable)jruby;
CompiledScript script;
script = compilingEngine.compile(code);
scripts.add(script);
return scripts.size()-1;
}
}
update
I thought this question was about avoiding to comile the source more than once.
Only other approach I could imagine is to create Java-Classes and make a cross-compile:
https://github.com/jruby/jruby/wiki/GeneratingJavaClasses
This question already has answers here:
Java execute command line program 'find' returns error
(2 answers)
Closed 10 years ago.
I am trying to execute a find command using java code. I did the following:
sysCommand = "find . -name '*out*' > file1"
Runtime runtimeObj = Runtime.getRuntime();
try {
Process processObj = runtimeObj.exec(sysCommand);
processObj.waitFor();
...
This Linux command is executed when I use command line but fails in Java, why?
As far as I know, it is not allowable to use any form of piping operator in Runtime.exec. If you want to move the results to a file, you will have to do that part in Java through Process.getInputStream.
If you are interested in doing this in Java then you will want to do something like this:
public void find(File startDirectory, FileFilter filter, List<File> matches) {
File[] files = startDirectory.listFiles(filter);
for (File file:files) {
if(file.isDirectory()) {
find(file, filter, matches);
} else {
matches.add(file);
}
}
}
Then you need but write the FileFilter to accept directories and files that match your pattern.
This question is probably a duplicate or a duplicate.
Anyway, you could use File.list, providing a Filter on the type
of files you want. You could call it recursively to get all sub-directories. I don't love this answer. You would think there is a simpler way.
A friend of mine recommended Commons-Exec from Apache for running a command. It allows you to use a time out on the command. He recommended it because Runtime can have issues with large stdout and stderr.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I run a batch file from my Java Application?
Are there Java classes to run Windows batch files? For example, start the batch files and receive the results of the batch runs?
Apache Commons Exec is a good way to go. Solves several problems you'd encounter if using pure ProcessBuilder or Runtime.exec.
From the project description:
Executing external processes from Java is a well-known problem area. It is inheriently platform dependent and requires the developer to know and test for platform specific behaviors, for example using cmd.exe on Windows or limited buffer sizes causing deadlocks. The JRE support for this is very limited, albeit better with the new Java SE 1.5 ProcessBuilder class.
The usual ProcessBuilder stuff works with batch files, as does Runtime#exec. The command you're executing is cmd.exe, the batch file name is an argument to it. I believe the argument sequence is cmd.exe, /c, batch_file_name. (Edit: Yup, and in fact, I found a question here that this question duplicates on SO where that's in the answer.)
Runtime.getRuntime().exec("cmd /c start batFileName.bat"); should work.
But to read the output from java process, remove start from the above comman.
Yes, according to my knowledge, RunTime classe can. And ofcourse, ProcessBuilder also like that. I have run number of batch files using Java. Following is the google search result. It has links which are equally important
GOOGLE RESULT
If you want to use native Java and no 3rd party packages then try this using Runtime and Process. I'm not the best Java coder in the world but this should get what you want. It might need some modification to add a loop for reading everything from the input stream.
import java.util.*;
import java.lang.*;
import java.io.*;
public class test
{
public static void main(String args[])
{
try
{
Runtime rt = Runtime.getRuntime();
Process batch = rt.exec("test.bat");
batch.waitFor();
//exitValue() contains the ERRORLEVEL from batch file
System.out.println(batch.exitValue());
//getInputStream will get all output from stdout
//getErrorStream will get all error output from stderr
InputStream inStream = batch.getInputStream();
byte[] text = new byte[inStream.available()];
inStream.read(text);
System.out.println(new String(text));
}
catch (IOException ex)
{
}
catch (InterruptedException ex)
{
}
}
}