How to avoid NoClassDefFoundErrors and NoSuchMethodErrors when targeting an older version of the JDK?

Suppose I want to write an application that focuses on a certain version of the JRE (for example, 1.6), but on the machine that I use to develop it, a newer version of the JRE is installed (for example, 1.7).

The naive approach is to set the compiler level to 1.6 (I use Eclipse, but this is probably not very important, since the problem is general). However, this is not enough. Setting the source level for the compiler ensures that the source files will only use the language features available for this version of Java, and therefore the generated class files have the correct minor version, so the target JVM will be able to load and run them.

But there is another and more subtle problem: if I use a class or method in my code that was added in 1.7 and try to run the application on a computer with version 1.6 installed, it does not work with NoClassDefFoundError or NoSuchMethodError .

The problem is that the same program works fine on the dev machine, since the 1.7 JDK installed on it contains these classes. The compiler or IDE also does not complain. The only indicators that I refer to classes and methods that will not be available are Since 1.7 comments in JavaDoc.

So, how do I ensure that I never use classes or methods that will not be available in an older version of the JRE? Is the only reliable solution to always have the exact version of the JRE in the build path? This would mean that I would need to install an additional JDK on my dev machine for each such case (1.7, 1.6, possibly 1.5 or even 1.4).

+4
source share
1 answer

Use the bootcpasspath parameter pointing to the 1.6 JRE (specifically rt.jar ) at compile time. This will force you to verify that all reference classes, methods, and attributes are indeed present in the supplied rt.jar .

See javac cross-compilation options for more details.

+3
source

Source: https://habr.com/ru/post/1435608/


All Articles