Which Java compilers are available on Windows? - java

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.

Related

Unable to use AbstractProcessor in IDEs

Motivation:
In our code we have a few places where some methods are run by their name. There are some big if-else-if blocks with each function name and call of the corresponding method (I use the term function to describe just names, for example function X01 might correspond to method SomeClass.functionX01). I've been looking into ways to improve that
Goal:
Write just methods that are annotated with some custom annotation, removing the need to update or even include if-else-if blocks in order to run specific function. Have access to any generated code if any code is generated.
What I did:
I've created first prove of concept using runtime annotations and it proved successful, but slower then if-else-if. Next attempt was with source annotation
I've followed this link for an example, however it did not seam to run in IntelliJ. What I wanted is to have - in this case PersonBuilder class generated, instead there was none. In some cases an error was raised Error:java: Bad service configuration file, or exception thrown while constructing Processor object: javax.annotation.processing.Processor: Provider BuilderProcessor not found
After some Googling and failing to find anything I've turned to book (Core Java, Volume II - Advanced Features - 9th Edition, Polish translation) and there was reccomended to run the following commands:
javac [AbstractProcessor implementation]
javac -processor [Compiled Processor] [other source files to compile]
This worked, however is unsatisfactory as it needs to happen inside IDE (NetBeans and IntelliJ to be specific) automatically during build. Code does not need to be generated on the fly, but programmer must have access to it after build (as in - be able to call methods of generated classes)
Question:
How to have and use generated code used in NetBeans and IntelliJ without the need of using external tools? Is it possible, or using reflection, runtime annotations or external tools is the only way?
Additional info (just in case):
Language level: Java 1.8
JVM versions: 12 and 13
IDEs: NetBeans and IntelliJ

How can I specify entry-point class and jar archive for JBCO (Java ByteCode Obfuscator)?

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.

java class method stubs with /* compiled code */

I just received a third party authentication library to use in my clients application. I didn't receive any documentation with it and am trying to dig through the source and see how it works. I'm very to new Java when i click Go To -> Declaration on methods in IntelliJ it sends me to a .class file and i see a bunch of stubbed methods with /* compiled code */ in the methods.
I'm fairly sure this is common in Java i just don't know what to search for to learn about what exactly is going on. Any clarification would be great.
This typically meant that you don't have the source code, and IntelliJ IDEA would just display /* compiled code */ as a placeholder for the source code you don't have. I believe this has now changed, and IntelliJ comes bundled with a full Java decompiler plugin, and will display the decompiled source code as standard.
To better see what's going on, the best would be to receive the actual source code of the third party library.
You should of course also get the documentation, as reading the source code and guessing how to use a library usually isn't the best way to learn.
The second best option would be use the decompiler plugin in IntelliJ, that will automatically decompile the Java class file (note that the license for your third party library may disallow you to do just that). This will never be a 100% solution, but in most cases it's better than nothing.
You should really search/ask for documentation. Javadoc usually is invaluable if the method does stuff you can't guess from its name. Otherwise use a decompiler such as JD-GUI.
.java sourcecode is compiled to .class bytecode by compilers such as javac. The compiler may optimise specific things, and a compilation-decompilation process if highly unlikely to yield the same source. Also, all comments should be deleted and if the code wasn't compiled in debug mode, even the variable names are lost. So: Decompilation is not a good alternative to handcrafted documentation.
If your library is build with sourceFiles:
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.sourceFiles//look at this line
}
Then you will see classes with /* compiled code */
If your library is build with srcDirs:
task androidSourcesJar(type: Jar) {
classifier = 'sources'
from from android.sourceSets.main.java.srcDirs//look at this line
}
Then you will see classes with full source without /* compiled code */

What if a native class/method only defined in a newer Java version?

As far as i know, during the compile time of Java, only the class/method signatures are recorded. The actual implementations are binded until the running time, in the JVM.
Let's imagine there is a native Java class called MyClass. And in Java version 1.6:
public class NativeClass {
public String getVersion() { return "1.6"; }
}
And in Java version 1.7:
public class NativeClass {
public String getVersion() { return "1.7"; }
public String somethingMore() { return "more"; }
}
Our IDE and compiler are 1.7. After the program compiled, when we run it in JRE 1.6 and 1.7, we will have different return values from NativeClass.getVersion();. This is known.
But what will happen if we run NativeClass.somethingMore() on JRE 1.6?
If possible, please give an example in the real Java source, where certain class/method only exist in a newer version.
But what will happen if we run NativeClass.somethingMore() on JRE 1.6?
A NoSuchMethodError will be thrown.
Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
What if a class that doesn't exist? There is no NoSuchClassError
See NoClassDefFoundError & ClassNotFoundException.
But don't ask me a) why there are two of them. b) why one is used over the other/what the difference is, or c) why methods also have NoSuchMethodException.
It seems they should all be an Error rather than an Exception.
Andrew Thomson is correct as far as he goes. Here's a more fulsome answer:
The first point is that if you compile code using a Java 1.7 SDK (or IDE), and try to run it on Java 1.6 (or earlier), you may run into a "magic number" error. Basically, unless the "target version" is set to the older version, the compiler will emit bytecode files that the older JVM cannot understand.
Once you have gotten past that:
Attempting to call a method that doesn't exist will result in a NoSuchMethodError.
Attempting to use (in any way) a class that doesn't exist will result in a ClassDefNotFoundError.
The errors are detected and thrown at the point when the JVM tries to resolve the dependencies between the classes. (This is referred as "linking" in the JLS. It happens some time before the class is "initialized", but the JVM is free to implement loading and linking lazily so it might not happen instantly on application startup.
Both of these are fatal errors. They leave the JVM in a state where the application is unlikely to be able to recover because an indeterminate set of the application's essential classes are not usable.
These are examples of "binary compatibility errors". Other examples include things like missing fields, methods with the wrong signatures, some changes in access modifiers, changes to the inheritance hierarchy, and so on. (There is a whole JLS chapter that deals with the binary compatibility rules; i.e. what you can and can't change in a class without breaking compatibility.)
This is all common sense really. If you attempt to call a method that isn't there or use a class that isn't there, bailing out with a fatal error is the only safe thing to do. There are practical limits to "write once, run anywhere".
If you want a simple example, try running an application that uses String.isEmpty() on a Java 1.5 or earlier JVM. (Or an early release Android phone ...)
You won't get a ClassNotFoundException. That is only thrown when you attempt to load classes using Class.forName(...).
This code works well with the latest MySQL JDBC driver - mysql-connector-5.1.22
Connection conn = DriverManager.getConnection"jdbc:mysql://localhost:3306/test", "root", "root");
conn.getSchema();
but if I use an older version, eg mysql-connector-5.1.20 I'll get
Exception in thread "main" java.lang.AbstractMethodError: com.mysql.jdbc.JDBC4Connection.getSchema()Ljava/lang/String;
at main.MySQL.main(MySQL.java:21)
because Connection.getSchema is since 1.7.
If a concrete class is missing, eg. Integer.compare(int, int) is since 1.7 you'll get java.lang.NoSuchMethodError
If a JRE class was missing, e.g. java.util.Scanner is since 1.5 and I used JRE 1.4 I would get java.lang.NoClassDefFoundError

Conditional Java compilation

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.

Categories

Resources