Convert String to callable methods in JAVA [duplicate] - java

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.

Related

Is it possible to view a Java class files bytecode [duplicate]

This question already has answers here:
Is it possible to view bytecode of Class file? [duplicate]
(5 answers)
Closed 7 years ago.
I am working on a bytecode manipulation/generation in Java and I was just wondering if there is an easy way I could check the bytecode. I do not want to decompile the file, I would like to actually look at the compiled bytecode. I do not need to edit it. Any links or programs for doing this would be acceptable answers.
Since you wanted to be guided to some program that can easily show you the byte code then my suggestion is to use IntelliJ IDEA since it has built-in support for viewing byte code.
Here's an example how to do it (it can also be mapped to some keys of your choice):
It is very easy, and it can surely be done in eclipse or NetBeans as well.
Not sure what exactly you need, but apart from javap, which is a command-line tool for displaying the bytecode, you can take a look at javassist, asm and cglib - they allow you to parse the bytecode with java code.
I've been working on a decompiler that has a color-coded bytecode output mode (which I find far more readable than javap). It can also output Java code or an intermediate 'bytecode AST'.
The javap command-line tool, which is bundled with Oracle's JDK, gives a detailed textual dump of .class files along with the constant pool and all functions' bytecode content. Just run it with -v to get a full dump.

How to run Java code using Java code?

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.

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.

Using Python from within Java [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Java Python Integration
I have a large existing codebase written in 100% Java, but I would like to use Python for some new sections of it. I need to do some text and language processing, and I'd much rather use Python and a library like NLTK to do this.
I'm aware of the Jython project, but it looks like this represents a way to use Java and its libraries from within Python, rather than the other way round - am I wrong about this?
If not, what would be the best method to interface between Java and Python, such that (ideally) I can call a method in Python and have the result returned to Java?
I'm aware of the Jython project, but
it looks like this represents a way to
use Java and its libraries from within
Python, rather than the other way
round - am I wrong about this?
Yes, you are wrong. You can either call a command line interpreter to run python code using Jyton or use python code from Java. In the past there was also a python-to-Java compiler, but it got discontinued with Jython 2.2
I would write a Python module to handle the text and language processing, and then build a small bridge in jython that your java program can interact with. The jython bridge will be a very simple one, that's really only responsible for forwarding calls to the python module, and return the answer from the python module to the java module. Jython is really easy to use, and setup shouldn't take you more than 15 minutes.
Best of luck!
I don't think you could use NLTK from Jython, since it depends on Numpy which isn't ported to the JVM. If you need NLTK or any other native CPython extension, you might consider using some IPC mechanism to communicate between CPython and the JVM. That being said, there is a project to allow calling CPython from Java, called Jepp:
http://jepp.sourceforge.net/
The reverse (calling Java code from CPython) is the goal of JPype and javaclass:
sourceforge.net/projects/jpype/
pypi.python.org/pypi/javaclass/0.1
I've never used any of these project, so I cant't vow for their quality.
Jython is a Python implementation running on the JVM. You can find information about embedding Python in an existing Java app in the user guide.
I don't know the environment that you're working in, but be aware that mixing languages in the same app can quickly lead to a mess. I recommend creating Java interfaces to represent the operations that you plan to use, along with separately-packaged implementation classes that wrap the Python code.
IN my opinion, Jython is exactly what you are looking at.
It is an implementation of Python within the JVM; as such, you can freely exchange objects and, for instance, inherit from a Java class (with some limitations).
Note that, its major strength point (being on top of of JVM) is also its major drawback, because it cannot use all (C)Python extension written in C (or in any other compiled language); this may have an impact on what you are willing to do with your text processing.
For more information about what is Jython, its potential and its limitations, I suggest you reading the Jython FAQ.
Simply run the Python interpreter as a subprocess from within Java.
Write your Python functionality as a proper script, which reads from stdin and writes to stdout.
Use the Java Runtime class to spawn a subprocess that runs your Python script. This is very simple to do and provides a very clean interface.
Edit
import simplejson
import sys
for request in sys.stdin.readlines():
args = simplejson.loads( request )
result = myFunction( args['this'], args['that'] )
sys.stdout.writeline( simplejson.dumps( result ) + "\n" )
The interface is simple, structured and very low overhead.
Remember to first check from those paying for the development that they're OK with the codebase needing a developer who knows both Python and Java from now on, and other cost and maintainability effects you've undoubtedly already accounted for.
See: http://www.acm.org/about/se-code 1.06, 2.03, 2.09, 4.03, 4.05, 6.07

Self modifying code in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Have you ever created or encountered a self modifying code in Java?
If yes, then please post the link or simply post the code.
Ignoring the world of grief you could be causing yourself via self-modifying code(!), it seems to me there are 3 options:
use the inbuilt compiler support of Java 6 and write/recompile/reload classes
use the Apache BCEL bytecode manipulation library to write your class directly
make use of Java 6's inbuilt scripting support (or use Apache BSF) to write methods in your JVM scripting language of choice, and execute these
Of the three above, my initial choice (in the absence of requirements) would be to take a look at option 3. I suspect it's the least painful way to start. I've used all of the above - unfortunately I can't post links to client code.
You can write (Java) code that generates new classes (byte code) at runtime using a library like bcel. That's not quite the same as self-modifying code. I suspect self-modifying code is not something the JVM supports.
For an example of generating new code at runtime, have a look at the source code of clojure.
That should be difficult to realize. But you can create at runtime new classes and load them with a custom classloader. If you want to modify the code again, you have to reload the class.
From BCEL:
The Byte Code Engineering Library is intended to give users
a convenient possibility to analyze, create, and manipulate
(binary) Java class files (those ending with .class).
Classes are represented by objects which contain all the
symbolic information of the given class: methods, fields and
byte code instructions, in particular.
I see these options for this purpose:
Generate the java source code and compile it with the external javac or the internal compiler tools (can't remember the name). And as you are responsible for the naming, just include a version count in the class name to avoid class loading anomalies.
Use the built in JavaScript engine support
Some scenarios can be solved using java Proxys
Edit: I once created a Java 1.4 program which took business rules from an existing legacy database, generated java files (basically implementations of a Predicate interface) with a bunch of println() from them and used the command line javac to compile them.
As an undergrad I got to work on the JikesRVM. It is a JVM implemented (mostly) in Java. At runtime it will JIT compile itself! It's a really cool piece of technology.
You could always just use a dynamic language...

Categories

Resources