2

I'm currently using gradle and it seems like I can set sourcecompatibility and targetcompatibility through java-plugin

I wonder what's the reasons for us to use sourcecompatibility/targetcompatibility other than to be backward compatible with older JDK?

would it be easier to upgrade to latest java if sourcecompatibility/targetcompatibility isn't set?

Should sourcecompatibility and targetcompatibility be used at all?

Tony
  • 81
  • 6

1 Answers1

2

The sourceCompatibility and targetCompatability variables are directly related to the -source and -target switches on javac. These are used for cross-compiling (relevant documentation for javac, relevant SO question). The sole purpose of these values is to make your class files backwards compatible. They don't really serve any other purpose. This is a feature that's added more or less for security purposes. Instead of installing an older, less secure JDK on your machine, you can install a newer one and use these values to compile your code.

These flags have one major caveat though: just because you set these values doesn't mean the code you write will work on older JVMs. This is because while javac will compile your classes to make them compatible with an older JVM, you can still end up binding to a method that doesn't exist in that older JVM.

For example, if you set your compatibility values to '1.6' and you're running your builds using JDK 8, you can still write code like this:

Objects.equals(obj1, obj2);

And the compiler will not complain. It will still build without complaining about that line. However, if you tried to run it with Java 6, you would get an error stating that Objects.equals doesn't exist because Objects was introduced in Java 7.

Put differently: -source and -target make your .class files compatible with older JVMs, but they do not validate classes and methods used by your code. The only way to do that is with -bootclasspath, at which point, you may as well just download and compile with the older JDK since you have to do that to get the rt.jar file needed for that (relevant SO question).

As far as upgrading is concerned, setting these values don't necessarily limit your ability to upgrade. Code you write will have to be compatible with whatever value you use if you plan on using it in that version, but nothing stops you from changing them and starting to use the newer features and APIs.

Brian
  • 17,079
  • 6
  • 43
  • 66