Sourcecompatibility targetcompatibility usage reasons

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?
Thank you very much for your help.

Cheers,
Tony

You can make sure that the source code is compatible with certain JDK, but should generate class files for use on another version of JDK. Why you would do this is another matter :wink:.

I think default Gradle uses installed JDK versions, isn’t?

https://docs.oracle.com/javase/6/docs/technotes/tools/windows/javac.html#crosscomp-options

yes? no? seems like the default right now is java 1.8 so it would be easier to upgrade to 9 by setting them to that.

but yes, this is primarily a way to be compatible with an older JVM, and or to set yourself to whatever language version your team want to use.

sourceCompatibility is a way to declare which version of Java your source code is compatible with. This has many implications, like telling the compiler which rules should apply to parse the code (for instance, enum started to be a reserved keyword only in Java5+) or how the IDE that integrates with your Gradle script should set up your project class path (for instance, if sourceCompatibility = 1.7, it should bind your project to a Java 7 JRE).

targetCompatibility, instead, is a way to declare which kind of byte code the compilation process should produce. By default, if not specified, targetCompatibility=sourceCompatibility. If you specify a targetCompatibility lower than sourceCompatibility, you’re trying to do something interesting in theory, but risky in practice, because either at compile time or just at runtime you may incur in “class not found” errors due to class path mismatch between what your source needs and what your compiler/runtime provides.

2 Likes