Skip to content

Instantly share code, notes, and snippets.

@raphw
Created June 4, 2014 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphw/8bbed14e906b94354e41 to your computer and use it in GitHub Desktop.
Save raphw/8bbed14e906b94354e41 to your computer and use it in GitHub Desktop.
This rule allows to write tests that are only executed if the running JVM supports Java 8 byte code.
public class Java8Rule implements MethodRule {
private final boolean java8OrHigher;
public Java8Rule() {
java8OrHigher = currentByteCodeLevel() >= (0 << 16 | 52);
}
@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
if (java8OrHigher || method.getAnnotation(Enforce.class) == null) {
return base;
} else {
return new NoOpStatement();
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Enforce {
/* empty */
}
private static class NoOpStatement extends Statement {
@Override
public void evaluate() throws Throwable {
/* do nothing */
}
}
private static int currentByteCodeLevel() {
String versionString = System.getProperty(JAVA_VERSION_PROPERTY);
int[] versionIndex = {-1, 0, 0};
for (int i = 1; i < 3; i++) {
versionIndex[i] = versionString.indexOf('.', versionIndex[i - 1] + 1);
if (versionIndex[i] == -1) {
throw new IllegalStateException("This JVM's version string does not seem to be valid: " + versionString);
}
}
return Integer.parseInt(versionString.substring(versionIndex[1] + 1, versionIndex[2]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment