| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
package org.aeonbits.owner.util; |
| 10 |
|
| 11 |
import java.lang.invoke.MethodHandles; |
| 12 |
import java.lang.invoke.MethodType; |
| 13 |
import java.lang.management.ManagementFactory; |
| 14 |
import java.lang.reflect.Constructor; |
| 15 |
import java.lang.reflect.InvocationTargetException; |
| 16 |
import java.lang.reflect.Method; |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
class Java8SupportImpl implements Reflection.Java8Support { |
| 22 |
private boolean isJava8; |
| 23 |
|
| 24 |
Java8SupportImpl() { |
| 25 |
String version = ManagementFactory.getRuntimeMXBean().getSpecVersion(); |
| 26 |
isJava8 = version.startsWith("1.8"); |
| 27 |
} |
| 28 |
|
| 29 |
@Override |
| 30 |
public boolean isDefault(Method method) { |
| 31 |
return method.isDefault(); |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
@Override |
| 36 |
public Object invokeDefaultMethod(Object proxy, Method method, Object[] args) throws Throwable { |
| 37 |
final Class<?> declaringClass = method.getDeclaringClass(); |
| 38 |
|
| 39 |
if (isJava8) { |
| 40 |
return Lookup.in(declaringClass) |
| 41 |
.unreflectSpecial(method, declaringClass) |
| 42 |
.bindTo(proxy) |
| 43 |
.invokeWithArguments(args); |
| 44 |
} else { |
| 45 |
MethodType rt = MethodType.methodType(method.getReturnType(), method.getParameterTypes()); |
| 46 |
return MethodHandles.lookup() |
| 47 |
.findSpecial(declaringClass, method.getName(), rt, declaringClass) |
| 48 |
.bindTo(proxy) |
| 49 |
.invokeWithArguments(args); |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
private static class Lookup { |
| 54 |
private static final Constructor<MethodHandles.Lookup> LOOKUP_CONSTRUCTOR = lookupConstructor(); |
| 55 |
|
| 56 |
private static Constructor<MethodHandles.Lookup> lookupConstructor() { |
| 57 |
try { |
| 58 |
Constructor<MethodHandles.Lookup> ctor = |
| 59 |
MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class); |
| 60 |
ctor.setAccessible(true); |
| 61 |
return ctor; |
| 62 |
} catch (NoSuchMethodException e) { |
| 63 |
return null; |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
private static MethodHandles.Lookup in(Class<?> requestedLookupClass) |
| 68 |
throws IllegalAccessException, InvocationTargetException, InstantiationException { |
| 69 |
return LOOKUP_CONSTRUCTOR.newInstance(requestedLookupClass, MethodHandles.Lookup.PRIVATE); |
| 70 |
} |
| 71 |
} |
| 72 |
} |