Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target a lower language level in Java

I maintain a Java tutorial application written in Java, that demonstrates features of Java 6, 7, and 8. Each tutorial screen is loaded dynamically by Class.forName as needed. The Java 7 classes need to use Java 7 constructs, and the Java 8 classes need to use Lambdas and Date/Time API.

I would like this to be accessible to users of all three of those language levels, just that if they are on Java 6 we would not load up the Java 7 or 8 classes, and if on 7 we would not load the Java 8 classes.

We would dynamically determine the runtime level and disregard higher levels, loading only the relevant classes by Class.forName(). Obviously users with Java 6 or 7 would not be able to execute code with a magic number of 8. So I would like to target an earlier Java release in the build.

In other words, I would like to set source to 1.8 and target to 1.6

However Maven (and Javac) prevent me from specifying a target lower than the source.

Is there any other way?

I have done this in the past with JavaFX code for Android, where I was able to build JavaFX 8 code using Lambdas, but then deploy it to current Android versions. But in that case, there was a special SDK that handled the lambdas and built to Java 7.

Is there any way to do that with standard Java 8?

like image 232
Victor Grazi Avatar asked Jan 29 '26 03:01

Victor Grazi


2 Answers

The only option you have is -source 1.1 -target 1.0 In every other case, they have to be the same

You need to build a jar for each version and another which combines them.

like image 61
Peter Lawrey Avatar answered Jan 31 '26 16:01

Peter Lawrey


You will have to make 3 different jars, one for each version where the later version include more of your code examples. (on the bright side, you just have to recompile the the java 6 and 7 code multiple times)

for each jar set the -target code to 6, 7 or 8 respectively. You can optionally also use -source parameter and set it to the same value but I don't think you need to unless you are worried you accidentally put in later language features.

like image 40
dkatzel Avatar answered Jan 31 '26 16:01

dkatzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!