Dynamic Java Compilation: BeanShell, Janino, JavaCompiler? - java

I am about to start developing a small Java desktop app. The app is just an engine for which the user provides Java classes to do the work (translating input to output).
I would like the user to provide actual Java classes as files that can be loaded (and reloaded) on the fly.
For this particular use, is there any reason why Java would be more cumbersome than Groovy or Beanshell? I'm not asking for a comparison of Groovy/Beanshell and Java as there are many. Rather, I want to know if it's easier to dynamically load Groovy or Beanshell classes from files compared to Java.
For Java 1.6, is the JavaCompiler the best way to dynamically load code? I would like to use all language features so I think Janino is out. Also, any problems with reloading?
Note: I have seen this and this, but I'm not sure they answer my question.

JavaCompiler is very versatile, but it entails a minor, potential configuration problem: In javax.tools, ToolProvider.getSystemJavaCompiler() identifies the compiler's class as com.sun.tools.javac.api.JavacTool. On some platforms, that class is not part of the JRE; a JDK appears to be required. Here is an example.
Also consider javax.script, discussed here. Several scripting engines are supported.

Related

java - Compile code on client side without JDK

I have a question which I'm pretty confused from.
I am aware of the differences between Java Runtime Enviroment and Java Developement Kit.
I'm writing a program that uses the ToolProvider.getSystemJavaCompiler() method to compile java code from within the code.
Now, I've been answered that I can't compile code from client side if my client doesn't have JDK installed. My main question is, how can I do that? I don't want my clients having to install JDK on their computer just to run my program.
Thanks in advance!
You need to compile it on your system, and distribute the class file of corresponding java source file to anyone.
That class file doesn't require JDK but JRE must be installed on that system to run the class file.
If you want to compile code, you need a compiler, so if the user can't be expected to have the compiler you need, you'll simply have to bundle it.
I really can't say I know how to bundle the standard javac compiler, though it's probably possible, strictly speaking, to find the Jar file that contains it and bundle that along with your code. No idea how robust such a solution would be, though.
But depending on your needs, you may not need the standard javac. There are tons of byte-code generation libraries out there, with more or less high-level functionality. I wouldn't really want to recommend anything that I have no personal experience with, but examples include Byte Buddy or ASM. You could probably use ABCL too.
Eclipse's compiler is worth a look as well.
There is also an so question here.
So there really is no way to do what it is you are wanting to do unless you bundle the compiler itself with you application, or unless you find a library that has all of the Java compiler code in it already so it doesn't have to use the JDK compiler, you will not get what you want, and what you want is the ability to turn a String containing source code into a Java class.
I do not understand what you wish to accomplish, but the BEST option I can give you is asm. If you are up for the task, you can manually write new classes at runtime without the presence of the JDK compiler. HOWEVER, this does not involve you using a String full of source code and turning it into a Class object. This is you working at the low level with the Java bytecode for the most part.
This tutorial can get you started:
https://www.javaworld.com/article/2071777/design-patterns/add-dynamic-java-code-to-your-application.html
And here is the Java documentation for class files. You can use this to expand on what you learned from the first link:
https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html
That is the only instance creating classes on the fly that I can give you. That being said, you could try writing your own Java compiler that can turn source code into classes without ever getting the Java compiler, but at that point you are literally recreating the Java compiler yourself, and I assure you that is no easy feat for one person.

Using a .net library from Java

I have a compiler for a domain specific language that outputs a .net dll (that can then be used to do whatever the DSL said it should). It works well under .net but now I need to make the compiled dll functionality accessible from Java. The interface changes depending on the DSL, much like it would if I was implementing an F# type provider.
Ideally, I would like something along the lines of Reflection.Emit except that it would generate Java bytecode. It is important that the end-user can debug their Java code that uses my generated library from a Java GUI, so I don't think I can just use IKVM to instead include the Java code in .net. I also cannot use a commercial product such as JNBridge because all the users would need to install it, and call it every time their DSL code changes.
Is there a better solution than generating a .java file in text format and compiling it with a Java compiler? The .java file would just be a light-weight interface talking to the .net dll over some IPC mechanism (perhaps a named pipe), and its purpose would be to provide a typesafe interface similar to what would be seen from a .net application (except with indexers, getters, setters, overloads, etc replaced with some sort of horribly verbose syntax). Many thanks.
Java native interface is a way to call native code from Java (That dll isn't running on the JVM, thats for sure). Throw your dreams of "Write once run anywhere" in the bin now.
If you want to use dlls then you have to use JNI (or something similar or based on JNI like jni4net). It's not as pleasant as say, using c++ from c#, but it's pretty doable and far and away the best way to use dlls from java (I think the second best is re-writing the native code).
Alternatively you could run a windows process alongside your java app and soap/json/namedpipes/etc between the two, is that what you suggest in the last paragraph?
This would be odd for a small solution, but for a larger modular project it's not so crazy. I would recommend using sockets to communicate between the two, because I think sockets are easiest. It says client/server in the example, but it could be two processes (java and f#). ... This causes problems for performance, synchronisation, firewalls etc.. ahhh, just use JNI.

Java without JVM

Just wondering if there are any Java implementations that work without a JVM. The reason I'm interested is, well, simply because I'm curious, and I was wondering if there were any "lightweight" Java implementations (without all the Sun libs attached).
I'm also interested in embedding Java in C++, but embedding the JVM in C++ seems rather ridiculous to me. I just want to exploit some of the Java language features in my C++ apps, but not exploit all the frivolous Java APIs.
EDIT:
I see from a lot of the answers I've gotten that I need to clarify...
I recently got in to developing node.js applications, which uses JavaScript. JavaScript in istelf is a language spec, it doesn't automatically come with the DOM, window.open, etc., although it did for a while. I'm wondering if there's something similar to Google's v8, except not for JavaScript, but for Java. In the end, I don't care if I can't write Hello World apps with it, I just want to be able to embed Java in a C++ application the way I can embed JavaScript in a C++ application with v8 or SpiderMonkey. If I could do that, then I could implement console output in C/C++ and then make that implementation callable from Java.
Do you want the Java VM alone without the API(STandard Library) ?
The JRE is composed by the JVM (Virtual MAchine) and the Standard Library, I have doubt that you can find a java implementation without the JVM ... You could find a compiler that compile java source code into native code(take a look at GCJ), but not a Java implementation without the VM.
Take a look at this wikipedia page to see some alternative Java implementations .
There's GCJ (GNU Compiler for Java), but the project has been deprecated since OpenJDK was open sourced.
there are light weight java processors designed for use in small devices for example JOP
As others have hinted, the "JVM" is the mechanism that knows how to load classes, interpret "bytecodes", and manage storage. It does not inherently include any of the java.lang... stuff, except that a few classes (String, Class, et al) are needed to represent classes and other basic data structures in the JVM.
As a result, Java without a JVM is just a bunch of meaningless bits.
There are (or were) compiled versions of Java that do/did not need the interpreter (though a reasonably compact interpreter is quite easy to build). A primitive class loader and some sort of storage management are still necessary, but class loading can be kept simple and for short-lived apps (or those that live with special restrictions) the storage manager need not do garbage collection.
As pstanton suggests, there are "lightweight" Java (or "Java-like") implementations that are suited for small devices.
IMHO, You need to re-exampine what it is you really want.
Java runtime consists of two main components
The JVM to run the code
The standard libraries which come with it.
You suggest you want to use Java, but you don't really have anything left without these.
For example, you cannot even write a "hello world" program without the libraries as String is a class in the JDK.

Runtime compilation in Java

I have started porting my server side C# app to Java. One of the things it does is dynamic generation of code using the CodeDOM framework, compiling it to bytecode, and loading the class during runtime. There are also scenarios where we have used Expression Tree for lightweight dynamic generation of methods.
I did some research and I believe the closest I came is Javaassist. I would appreciate if there are any other frameworks that supports dynamic code generation and compilation. I am a fresh recruit in the Java world.
There's the Java Compilation API (for example, http://www.accordess.com/wpblog/an-overview-of-java-compilation-api-jsr-199/).
If you just need to evaluate expressions, consider any EL, like OGNL or MVEL.
Groovy, JRuby, and Scala are the most mainstream dynamic languages that allow a huge range of options, from simple expression evaluation to full-blown Java interaction.
To modify classes, you can use javaassit, asm, cglib(actually, it depends on asm), bcel, and etc.
Among them, I recommend asm, because of its better lightweight and better performance.
Using asm, you can generate some classes dynamically. But if you want to modify the classes, which are running in the jvm, you have to use Java Instrument API to retransform the existed classes.
You can see this paper for more info. http://www.cs.helsinki.fi/u/pohjalai/k05/okk/seminar/Aarniala-instrumenting.pdf
More doc about Instrument from oracle.
http://docs.oracle.com/javase/6/docs/technotes/guides/instrumentation/index.html
I have successfully used Janino for dynamic code generation. Like Javassist, it can compile Java source code in-memory. Also like Javassist, it lacks Java 1.5 language features, but apart from that it is easy to use.
The SimpleCompiler class is a good starting point.
I would look at lisp (or other dynamic languages) that have been targeted to jvm.
wiki article

Combining Java and C without gcj -- move C to Java or Java to C?

First, I have no experience doing this. But like the beginning of any good program, I have problem that I need to fix, so I'm willing to learn.
So many of you are probably already familiar with pdftk, the handy utility for handling various pdf-related tasks. So far as I can tell, most of these features are available in much newer, lighter libraries/extensions, except the one I need (and probably the only reason it still exists): merging form data files (fdf and xfdf) with a form PDF and getting a new file as the output.
The problem is that my server doesn't have gcj, which is fundamental to build/compile pdftk. I don't know if it's because I'm on Solaris or if it's for some other sysadmin-level reason, but I'm not getting gcj anytime soon. And there are no pre-compiled binaries for Solaris as far as I can find.
So I'm thinking that the MAKE file and C code can be rewritten to import the Java library (very ancient version of itext) directly, via javac.
But I'm not sure where to really start. All I know is:
I want a binary when I'm done, so that there won't be a need for a Java VM on every use.
The current app uses GCJ.
So my first thought was "Oh this is easy, I can probably just call the classes with some other C-based method", but instead of finding a simple method for doing this, I'm finding tons of lengthy posts on the various angles that this can be approached, etc.
Then I found a page on Sun's site on how to call other languages (like C) in a Java class. But the problems with that approach are:
I'd have to write a wrapper for the wrapper
I'd probably be better off skipping that part and writing the whole thing in Java
I ain't ready for that just yet if I can just import the classes with what is already there
I'm not clear on if I can compile and get a binary at the end or if I'm trapped in Java being needed every time.
Again, I apologize for my ignorance. I just need some advice and examples of how one would replace GCJ dependent C code with something that works directly with Java.
And of course if I'm asking one of those "if we could do that, we'd be rich already" type questions, let me know.
I'm not sure what you are looking for exactly, so I provided several answers.
If you have java code that needs to run, you must:
Run it in a jvm. You can start that vm within your own custom c-code, but it is still using a jvm
Rewrite it in another language.
Compile with an ahead-of-time compiler (eg gcj)
Incidentally, you could compile a copy of gcj in your home folder and use that. I believe the magic switch is --enable-languages=java,c (see: here for more)
If you have c-code you want to call from java, you have four options:
Java Native Interface (JNI). It seems you found this
Java Native Access (JNA). This is slower than JNI, but requires less coding and no wrapper c-code. It does require a jar and a library
Create a CLI utility and use Runtime.Exec(...) to call it.
Use some sort of Inter Process Communication to have the Java code ask the c-code to perform the operation and return the result.
Additional platform dependent options
Use JACOB (win32 only: com access)
I am not sure if I understand what you are looking for.
If you are looking to incorporate the C code into Java to make a native binary without the gcj, I think you are out of luck. You can include the C in Java, but it would be a primarily Java program meaning you would need the JVM on each run. Is there anything stopping you from compiling the gcj yourself?

Categories

Resources