Are there any options other than Janino for on-the-fly compiliation and execution of Java code in v5? I know v6 has the Compiler API, but I need to work with the v5 VM.
I essentially need to take a string containing a complete Java class, compile it and load it into memory.
What you want is something like Janino. We've used it for years. You give it (near standard) code and it gives you the classes so you can use them. It actually has quite a few different modes and supports the 1.5 syntactic sugar and auto-boxing and such.
If you call javac, not only will you have to be ready for anything it does, you'll then have to handle putting the class in the right place or making an additional classloader.
Janino is very easy. It should be exactly what you are looking for.
Invoking javac programatically:
http://www.juixe.com/techknow/index.php/2006/12/12/invoke-javac-at-runtime/
com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
String[] options = new String[]
{
"-classpath", classpath, "-d", outputDir, filename
};
javac.compile(options);
All app servers do this for JSP for ever, so obviously it is possible. Checkout tomcat source code maybe?
Related
I can't guess how can I specify class, which is entry-point of my program (therefore shouldn't be obfuscated), and my jar archive. Please show me an command-line example, how to use JBCO when I have /home/example/myJar.jar and within it com.example.EntryPoint class and my external dependency /home/example/dependencies/dependencyJar.jar.
Also, please, does anybody know if this project is still alive and what jdk it supports?
A lot of time have passed, but recently I have passed across the java transformation frameworks and find out that JBCO now is a part of soot framework, hosted on GitHub, but it is #deprecated as for now. There is a wiki where you can get more info about how to use soot/jbco (if you still want to, on your own risk, even though JBCO is deprecated and not under active development it still from time to time accepts PRs from contributors).
As for the command line options it might be:
java -cp .:/home/example/sootclasses-trunk-jar-with-dependencies.jar soot.jbco.Main -process-dir /home/example/compiled -output-dir /home/example/obfuscated -soot-class-path .:/home/example/myJar.jar -output-format class -app -main-class com.example.EntryPoint -t:9:wjtp.jbco_cr
Soot can process your compiled code as class files (then pass it to -process-dir option) or as jar (then pass it as part of soot-class-path) - soot can process many forms of bytecode (java/scala/.. bytecode, android bytecode, jasmin, jimple). There are also options to specify what is library classes and application or argument classes more precisely, for more info please refer to soot's wiki page.
I have a set of ruby files where I have some string of type:
#something = [Whatever.new('1rabbit'),
Whatever.new('2rabbit'),
Whatever.new('3rabbit')]
I would like to parse out this information from the ruby file during compilation phase (javac run with maven - but i think it is no difference how javac is run), and create a .class enum of type:
public enum Something {
1RABBIT,
2RABBIT,
3RABBIT
}
and store it into the target folder. Then, I can use this enum whatever I want (after this initial compilation). I looked into AnnotationProcessors, and bytecode generation, but the first requires annotations, and the second is done during runtime. And I cannot find out how to do it properly.
What is the correct tool to do this, and how?
mavens life cycle has a generate sources phase. There you cold use the exec-maven-plugin to run a script generating the enums.
Is there a way to create a new java class during execution? All the information about the class (name, modifiers, methods, fields, etc.) exists. Now I want to create that class. An idea was to create a new file and write the stuff to that file, c'est fini! But I think there are more elegant ways to do that, maybe with JDT?
Either use BCEL to create byte code and class files (the hard way) or create the source code in memory and use the Java 6 Compiler API (that's what I would do). But with Compiler API you need a Java SDK while running the application, a JRE is not sufficient.
Further Reading
The Java 6.0 Compiler API
(There a lot of tutorials on the web)
If you are writing an eclipse plugin and you want your tooling to generate code into a project, you can interact with JDT using the AST. There is also a method to call the Eclipse batch compiler from your runtime.
AST ast = AST.newAST(AST.JLS3);
CompilationUnit unit = ast.newCompilationUnit();
PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
packageDeclaration.setName(ast.newSimpleName("example"));
unit.setPackage(packageDeclaration);
ImportDeclaration importDeclaration = ast.newImportDeclaration();
QualifiedName name =
ast.newQualifiedName(
ast.newSimpleName("java"),
ast.newSimpleName("util"));
importDeclaration.setName(name);
importDeclaration.setOnDemand(true);
unit.imports().add(importDeclaration);
TypeDeclaration type = ast.newTypeDeclaration();
type.setInterface(false);
type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
type.setName(ast.newSimpleName("HelloWorld"));
// ....
Long winded :-) but you have access to the JDT java core model as you go.
If you need to generate files into your eclipse workspace, there are also template based options, like JET.
But if you want to dynamically generate and load a .class file in the runtime of a java application try #Andreas_D suggestions.
Look at code generation libraries,
http://cglib.sourceforge.net/
http://www.csg.is.titech.ac.jp/~chiba/javassist/
So, long story short, I need to use another Java compiler than what came with my Eclipse installation(Windows). I have to run some code that runs well in my other team member's computers (osx) but fails to run here. It seems the compiler I am using is way more strict than theirs, so I am looking for a more relaxed compiler (until they fix their code to comply to my actual compiler).
What are the options available?
So, a totally stripped down version of the code is like this:
public class TreeSet <E extends Xpto & IOrderable<E>> implements SortedSet<E>, Cloneable {
...
}
public interface Xpto {}
interface IOrderable<E> extends Cloneable{
boolean greaterEq(E e);
IOrderable<E> clone();
}
being the error
"The inherited method Object.clone()
cannot hide the public abstract method
in IOrderable"
You have these options
Sun/Oracle (recommended)
IBM Jikes
gjc
But your main description sounds more like build specific problem. You can tweak them by right click on the project->Properties->Java Compiler.
UPDATE Clonable already provides a clone Method which is hidden. So you should strip that line from the IOrderable interface. In TreeSet clone has to be public.
Eclipse uses its own built-in one. You should probably try using the one which comes with the JDK.
Alternatively, have you tried changing the Eclipse compiler options, there's a lot you can tweak, including whether some code ends up with errors, warnings, or nothing. Look in either the project preferences or your workspace preferences, under Java > Compiler > Errors/Warnings. If you could give an example of the errors you're getting (and ideally the code which is failing), we could give more advice.
You should use an Ant build script, which when executed will in turn use the normal Sun Java compiler. See here for a simple build script. It's a good way of getting around the problems :)
Eclipse probably uses the one in the JDK, right? (wrong. from the comments: according to 1 commenter and 3 upvoters, Eclipse uses its own internal compiler, my bad. But that means you can use the one in the JDK too :D)
Anyway, you can try http://en.wikipedia.org/wiki/GCJ
Comments suggest this is not a compiler, although I do not agree. Please educate me on my wrongness and I'll gladly update or remove this answer.
From the wikipedia page :
The GNU Compiler for Java (GCJ or gcj)
is a free software compiler for the
Java programming language and a part
of the GNU Compiler Collection. GCJ
can compile Java source code to either
Java Virtual Machine bytecode, or
directly to machine code for any of a
number of CPU architectures. It can
also compile class files containing
bytecode or entire JARs containing
such files into machine code.
I'm a longtime C++ programmer, new to Java. I'm developing a Java Blackberry project in Eclipse. Question - is there a way to introduce different configuration sets within the project and then compile slightly different code based on those?
In Visual Studio, we have project configurations and #ifdef; I know there's no #ifdef in Java, but maybe something on file level?
You can set up 'final' fields and ifs to get the compiler to optimize the compiled byte-codes.
...
public static final boolean myFinalVar=false;
...
if (myFinalVar) {
do something ....
....
}
If 'myFinalVar' is false when the code is compiled the 'do something....' bit will be missed out of the compiled class. If you have more than one condition - this can be tidied up a bit: shift them all to another class (say 'Config.myFinalVar') and then the conditions can all be kept in one neat place.
This mechanism is described in 'Hardcore Java'.
[Actually I think this is the same mechanism as the "poor man's ifdef" posted earlier.]
you can manage different classpath, for example, implement each 'Action' in a set of distinct directories:
dir1/Main.java
dir2/Action.java
dir3/Action.java
then use a different classpath for each version
javac -sourcepath dir1 -cp dir2 dir1/Main.java
or
javac -sourcepath dir1 -cp dir3 dir1/Main.java
In JDK6, you can do it by using Java's ServiceLoader interface.
Check it here.
If you want this specifically for BlackBerry, the BlackBerry JDE has a pre-processor:
You
can enable preprocessing for your
applications by updating the Eclipseâ„¢
configuration file.
In C:\Program Files\Eclipse\configuration\config.ini,
add the following line:
osgi.framework.extensions=net.rim.eide.preprocessing.hook
If you enable preprocessing after you
have had a build, you must clean the
project from the Project menu before
you build the project again.
Then you can do things in the code like:
//#ifdef SOMETHING
// do something here
//#else
// do something else
//#endif
For details see Specifying preprocessor defines
Can one call that a poor mans ifdef: http://www.javapractices.com/topic/TopicAction.do?Id=64?
No, Java doesn't have an exact match for that functionality. You could use aspects, or use an IOC container to inject different implementation classes.
You can integrate m4 into your build process to effectively strap an analogue to the C preprocessor in front of the Java compiler. Much hand-waving lies in the "integrate" step, but m4 is the right technology for the text processing job.
Besides Maven, Ant and other build tools that provide similar functionality, one would rather build interfaces in Java and switch the implementations at Runtime.
See the Strategy Pattern for more details
In opposite to C/C++ this will not come with a big performance penality, as Javas JIT-compiler optimizes at runtime and is able to inline this patterns in most cases.
The big pro of this pattern is the flexibility - you can change the underlying Implementation without touching the core classes.
You should also check IoC and the Observer Pattern for more details.
You could use maven's resource filtering in combination mit public static final fields, which will be indeed get compiled conditionally.
private static final int MODE = ${mode};
...
if (MODE == ANDROID) {
//android specific code here
} else {
}
Now you need to add a property to your maven pom called "mode", which should be
of the same value as your ANDROID constant.
The java compiler should (!) remove the if and the else block, thus leaving your android code.
Not testet, so there is no guarantee and i would prefer configuration instead of conditional compilation.
There are a couple of projects that bring support for comment-based conditional compilation to Java:
java-comment-preprocessor
JPSG
Example in JPSG:
/* with Android|Iphone platform */
class AndroidFoo {
void bar() {
/* if Android platform */
doSomething();
/* elif Iphone platform */
doSomethingElse();
/* endif */
}
}
In eclipse you could use multiple projects
Main (contains common code)
Version1 (contains version1 code)
Version2 (contains version2 code)
Main -> Select Project->Properties->Java Build Path->Projects tab
Select Add...
Add "Version1" xor "Version2" and OK back to the workspace.
Version1 and Version two contain the same files but different implementations. In Main you normally write e.g.
import org.mycustom.Version;
And if you included Version1/Version2 project as reference it will compile with the Version.java file from Version1/Version2 project.