|
| 1 | +package me.zort.sqllib; |
| 2 | + |
| 3 | +import java.lang.invoke.MethodHandles; |
| 4 | +import java.lang.invoke.MethodType; |
| 5 | +import java.lang.reflect.Constructor; |
| 6 | +import java.lang.reflect.Method; |
| 7 | + |
| 8 | +public abstract class JVM { |
| 9 | + |
| 10 | + public abstract Object invokeDefault(Class<?> declaringClass, Object instance, Method method, Object[] args) throws Throwable; |
| 11 | + |
| 12 | + public static JVM getJVM() { |
| 13 | + int ver = jvmVer(); |
| 14 | + if (ver < 8) |
| 15 | + throw new UnsupportedOperationException("Unsupported JVM version: " + ver); |
| 16 | + else if (ver == 8) |
| 17 | + return new JVM8(); |
| 18 | + else |
| 19 | + return new JVM9(); |
| 20 | + } |
| 21 | + |
| 22 | + private static int jvmVer() { |
| 23 | + String version = System.getProperty("java.version"); |
| 24 | + if(version.startsWith("1.")) { |
| 25 | + version = version.substring(2, 3); |
| 26 | + } else { |
| 27 | + int dot = version.indexOf("."); |
| 28 | + if(dot != -1) { |
| 29 | + version = version.substring(0, dot); |
| 30 | + } |
| 31 | + } |
| 32 | + return Integer.parseInt(version); |
| 33 | + } |
| 34 | + |
| 35 | + |
| 36 | + static final class JVM8 extends JVM { |
| 37 | + @Override |
| 38 | + public Object invokeDefault(Class<?> declaringClass, Object instance, Method method, Object[] args) throws Throwable { |
| 39 | + Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class); |
| 40 | + constructor.setAccessible(true); |
| 41 | + return constructor.newInstance(declaringClass) |
| 42 | + .in(declaringClass) |
| 43 | + .unreflectSpecial(method, declaringClass) |
| 44 | + .bindTo(instance) |
| 45 | + .invokeWithArguments(args); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + static final class JVM9 extends JVM { |
| 50 | + @Override |
| 51 | + public Object invokeDefault(Class<?> declaringClass, Object instance, Method method, Object[] args) throws Throwable { |
| 52 | + MethodHandles.Lookup lookup = MethodHandles.lookup(); |
| 53 | + return lookup.findSpecial(declaringClass, method.getName(), MethodType.methodType(method.getReturnType(), method.getParameterTypes()), declaringClass) |
| 54 | + .bindTo(instance) |
| 55 | + .invokeWithArguments(args); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments