How to run Java code using Java code? - java

Basically, I want to do two things:
I want to know if there is any way that I can run Java code using Java code.
If it is possible, how would I show the output on my screen? (be it regular output or error or exception)
I know this is possible because one of my seniors had done it, but I don't know how he did it. Maybe he used one of Java's built-in classes.
Note: user will write the code in some text file and then I will store that file content in some variable and then maybe run that code.

Yes, it is possible.
Step 1: Compile the Code
Use ProcessBuilder or Runtime to construct a Process in which the Java compiler compiles their code. (Note that this requires that a Java compiler be available on the system at runtime).
Step 2: Invoke their Code
There are two ways to invoke their code. You can again use a ProcessBuilder or Runtime object to construct a process in which you execute their Java code. You can use the Process's getInputStream and getOutputStream functions to read from and write to the other process. An alternative is that you can use Class and the various reflection APIs to load their code and execute it directly within Java.

You would have to some how invoke a compiler (such as Suns javac), parse its output in case of errors and load the resulting classes dynamically.
There is no API-classes in the Java runtime library that will parse, compile and run Java source code.

If you want an interpreter (so, no compiling required) for Java, take a look at BeanShell.
I like this one very much!

You can use a scripting language running on top of the JVM. Groovy is a very good idea and it has very similar syntax compared to Java.

Related

Convert String to callable methods in JAVA [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert String to code in Java
Dynamic code execution on Java
I have a String containing : "for(int i=0 ; i<5 ; i++){System.out.println(\"*\");}"
Can I execute the code in this String in Java?
Since Java 6, you can compile and run a Java compilation unit defined as a String or a File using standard APIs in the SDK (a compilation unit is basically everything that goes inside a .java file - package, imports, classes/interfaces/enumerations), take a look at this example. You can't run an arbitrary Java snippet like the one in your question, though.
If at all possible, it'd be a better idea to embed a different scripting language that allows you to run snippets of code from a Java program - for example, JavaScript, Groovy, MVEL, BeanShell, etc.
If you turn it into a full-blown source file, you can feed it to the java compiler programmatically, but last time I checked that was only available if you had the java SDK installed on your machine; it was not available on machines with the client distribution of Java. Of course, this may have changed since then. Look at package com.sun.tools.javac and you will find the java compiler API there.
Maybe you can run this as Groovy:
http://groovy.codehaus.org/Embedding+Groovy
There isn't a Java Core API function for doing this, but you can call javac either by using Runtime.exec or using some "unsafe" classes from com.sun.tools.javac Here's an example:
http://juixe.com/techknow/index.php/2006/12/12/invoke-javac-at-runtime/
I don't think you can execute a String containing a java code.
But it is worth a try if you can save that as a java source file and try to use ProcessBuilder class to execute.
Never tried it and not sure if it is best way to do it. So use it with caution :)
Good Luck!
Also found a similar post: Runtime class in java
No, you can not execute this code in your program.

Java bytecode compiler in JavaScript

I'm looking for a standard Java to Java bytecode compiler implemented in JavaScript.
Has anyone heard of anything that can accomplish this?
There are several here: https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS
Such as j2js, bicavm, doppio...(see the java section)
if your goal is to have users write Java in a browser and see it run, it makes.MUCH more sense to do the compiling and executing server side. A servlet could read the code, compile it and run it, then push the output back to the browser.
unless your thesis is "Anything that can be written in JavaScript will eventually be written in JavaScript."

compiling java from within python

I'm making an application where people can upload a java code and do stuff with it.
The application i'm making is in Python. I was wondering whether it was possible to call the 'javac' command from within python, in order to compile the uploaded java file
I'm also using JPype
http://docs.python.org/library/subprocess.html
But are you sure that allowing people to submit arbitrary code is a good idea? There are security aspects of that to consider...
Entirely possible: just use the system command and invoke the java compiler. You'll probably need to set class paths and things of that nature, but it should work fine.
EDIT: see http://docs.python.org/library/os.html#os.system and http://docs.python.org/library/subprocess.html#module-subprocess for detail on invoking sub processes. You'll probably want to capture the output to return to the user in the event of a compile error.

Programming an Interpreter for a Compiler

I'm writing an interpreter for a compiler program in Java. So after checking the source code, syntax and semantics, I want to be able to run the source code, which is the input for my compiler. I'm just wondering if I can just translate some tokens, for example, out (it prints stuff on screen), can I just replace it with System.out.print? then feed the source code again to run it in java?
I've heard of using the Java Compiler API, would this be a good plan?
Thank you very much in advance!
What you asking is a virtual machine implementation technique, to run your Java code in general you should implement following:
The first few steps I guess you already done (Design/describe the language semantics, construct AST and perform required validation of the code)
You need to generate your byte code, original Java works exactly in the same way, it generates another representation of the source code, from human readable to machine readable.
Here you can see how Java byte code looks like http://www.ibm.com/developerworks/ibm/library/it-haggar_bytecode/
You need to implement virtual aka stack machine that reads byte code and runs it for execution.
So as you can see you should have 3 separated components (projects) for your task:
1. Language grammar
2. Compiler (byte code generator)
3. Virtual machine (interpreter of byte code)
P.S. I have experience in creation of tiny Java similar compiler from scratch (define grammar with ANTlr, implementation of compiler, implementation of virtual machine), so probably I can share more information with you (even source code) if you need something particular
You really need to read some books and/or take courses on compilers - this can't be solved by a two-paragraph answer on SO.
You could create a cross-compiler which reads your language and outputs Java code to do the same thing. This may be the simplest option.
The Java Compiler API can be used to compile Java code. You would need to translate your existing code to Java first to use it.
This would not be the same thing as writing an interpreter. Is this homework? Does the task say you have to write the interpreter or can you have the code run any way which works?
Unfortunately you did not mention which scripting language are you planning to support. If it is one of well known languages, just use its ready interpreter written in pure java. See BSF and Java 5 scripting (http://www.ibm.com/developerworks/java/library/j-javascripting1/)
It it is your own language
think twice: do you really need it?
If you are sure you need your own language think about JavaCC
First of all, thank you very much for the fast replies.
As part of our compiler project, we need to be able to compile and run a program written in our own specified language. The language is very similar to C. I am confused on how an interpreter works, is there a simpler way to implement this? Without generating byte codes? My idea was to translate each statement into Java equivalent statements, and let Java handle the byte code generation.
I would look into the topics mentioned. Again, thank you very much for the suggestions.

Understanding Java Byte Code

Often I am stuck with a java class file with no source and I am trying to understand the problem I have at hand.
Note a decompiler is useful but not sufficient in all situation...
I have two question
What tools are available to view java byte code (preferably available from the linux command line )
What are good references to get familiar with java byte code syntax
Rather than looking directly at the Java bytecode, which will require familiarity with the Java virtual machine and its operations, one could try to use a Java decompiling utility. A decompiler will attempt to create a java source file from the specified class file.
The How do I “decompile” Java class files? is a related question which would be informative for finding out how to decompile Java class files.
That said, one could use the javap command which is part of the JDK in order to disassemble Java class files. The output of javap will be the Java bytecode contained in the class files. But do be warned that the bytecode does not resemble the Java source code at all.
The definite source for learning about the Java bytecode and the Java Virtual Machine itself would be The Java Virtual Machine Specification, Second Edition. In particular, Chapter 6: The Java Virtual Machine Instruction Set has an index of all the bytecode instructions.
To view bytecode instruction of class files, use the javap -v command, the same way as if you run a java program, specifying classpath (if necessary) and the class name.
Example:
javap -v com.company.package.MainClass
About the bytecode instruction set,
Instruction Set Summary
Fernflower is an analytical decompiler, so it will decompile classes to a readable java code instead of bytecodes. It's much more usefull when you want to understand how code works.
If you have a class and no source code, but you have a bug, you can do one of two basic things:
Decompile, fix the bug and recreate the jar file. I have done this before, but sysadmins are leery about putting that into production.
Write unit tests for the class, determine what causes the bug, report the bug with the unit tests and wait for it to be fixed.
(2) is generally the one that sysadmins, in my experience, prefer.
If you go with (2) then, in the meantime, since you know what causes the bug, you can either not allow that input to go to the class, to prevent a problem, or be prepared to properly handle it when the error happens.
You can also use AspectJ to inject code into the problem class and change the behavior of the method without actually recompiling. I think this may be the preferable option, as you can change it for all code that may call the function, without worrying about teaching everyone about the problem.
If you learn to read the bytecode instructions, what will you do to solve the problem?
I have two question
1) What tools are available to view java byte code (preferably available
from the linux command line )
The javap tool (with the -c option) will disassemble a bytecode file. It runs from the command line, and is supplied as part of the Java SDK.
2) What are good references to get familiar with java byte code syntax
The javap tool uses the same syntax as is used in the JVM specification, and the JVM spec is naturally the definitive source. I also spotted "Inside the Java Virtual Machine" by Bill Venners. I've never read it, and it looks like it might be out of print.
The actual (textual) syntax is simple and self explanatory ... assuming that you have a reference that explains what the bytecodes do, and that you are moderately familiar with reading code at this level. But it is likely to be easier to read the output of a decompiler, even if the bytecodes has been fed through an obfuscator.
You might find the Eclipse Byte Code Outline plugin useful:
http://andrei.gmxhome.de/bytecode/index.html
I have not used it myself - just seen it mentioned in passing.

Categories

Resources