In the JavaScript world it often happens that a user's browser does not implement a feature but it can be supported by adding some additional code as a work-around. This is often called a "shim" (or "shiv"). In C I have done something similar at compile-time using preprocessing like #define ENABLE_XYZ_SUPPORT 1
and then #if ENABLE_XYZ_SUPPORT 1
.
Is there something like this in Java? Namely, I would like to be able to compile some source code designed for Java 1.7 with Java 1.6. Perhaps there is a library for this if there is no built-in language construct?
Background: I am somewhat new to Java and am developing my first significantly large project (basically a servlet that conditionally assembles data from various sources). Since this is a brand new project it seemed reasonable to take advantage of some of the new features of Java 1.7 such as implementing the AutoCloseable
interface for objects rather than just Closeable
so that they could be used with try-with-resources
. However, it would be nice if this application could be built to run on Java 1.6 as well in case it needed to. If I could add a parameter or something to enable defining my own AutoCloseable
interface then this could compile since I am not actually using try-with-resources
-- just trying to use the most appropriate interfaces.
I realize that I could do something like have maven run an external tool to replace AutoCloseable with Closeable if it were building for 1.6. However, that's not really what I'm looking for (not general enough).
Update: To clarify, I'm wondering if I can do something conditionally at compile-time like this:
#if java version < 1.7
public interface AutoCloseable {
void close() throws Exception;
}
#endif
BTW, I am using maven with this project, so if it has a feature that would help here that might be worth considering.
You can't run java code that makes uses of the new construct of java 7 (such as try-with-resources
) on java 6 JVMs, so there's no compiler or code trick that will help you on that, unfortunately. You should have two codebases if you want to support and old version.