Comment #2 on issue 497 by
phjar...@gmail.com: Mock returning
Why not dynamically include modules if a required Java version (or any
other library) is present?
The Spring Framework does something like this in many places, mainly to
load plugins depending on the presence of a certain class in the class
path. See
https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/web/client/RestTemplate.java#L130
Demo code that loads a class only if the Java version meets a certain
requirement follows (with console output and simplified error handling to
keep things simple).
public final class DynamicImport {
private static final int JAVA_VERSION;
static {
final String versionString = System.getProperty("java.version");
final Matcher matcher =
Pattern.compile("^1\\.(\\d+)\\.\\d+_\\d+$").matcher(versionString);
if (!matcher.matches()) {
throw new IllegalStateException(String.format("Can't parse Java version
[%s]", versionString));
}
JAVA_VERSION = Integer.parseInt(matcher.group(1));
}
private DynamicImport() {
// utility class
}
public static void includeClass(final int minVersion, final String
className, final ClassLoader loader) {
if (JAVA_VERSION < minVersion) {
System.out.println(String.format("Skipping loading of class [%s]: Java
version %d is lower than required %d", className,
JAVA_VERSION, minVersion));
return;
}
try {
System.out.println(String.format("Loading class [%s]", className));
Class.forName(className, true, loader);
} catch (final ClassNotFoundException e) {
throw new IllegalStateException(String.format("Error loading class
[%s]: %s", className, e), e);