|
| 1 | +package feign; |
| 2 | + |
| 3 | +import feign.InvocationHandlerFactory.MethodHandler; |
| 4 | +import org.jvnet.animal_sniffer.IgnoreJRERequirement; |
| 5 | + |
| 6 | +import java.lang.invoke.MethodHandle; |
| 7 | +import java.lang.invoke.MethodHandles.Lookup; |
| 8 | +import java.lang.reflect.Field; |
| 9 | +import java.lang.reflect.Method; |
| 10 | + |
| 11 | +/** |
| 12 | + * Handles default methods by directly invoking the default method code on the interface. |
| 13 | + * The bindTo method must be called on the result before invoke is called. |
| 14 | + */ |
| 15 | +@IgnoreJRERequirement |
| 16 | +final class DefaultMethodHandler implements MethodHandler { |
| 17 | + // Uses Java 7 MethodHandle based reflection. As default methods will only exist when |
| 18 | + // run on a Java 8 JVM this will not affect use on legacy JVMs. |
| 19 | + // When Feign upgrades to Java 7, remove the @IgnoreJRERequirement annotation. |
| 20 | + private final MethodHandle unboundHandle; |
| 21 | + |
| 22 | + // handle is effectively final after bindTo has been called. |
| 23 | + private MethodHandle handle; |
| 24 | + |
| 25 | + public DefaultMethodHandler(Method defaultMethod) { |
| 26 | + try { |
| 27 | + Class<?> declaringClass = defaultMethod.getDeclaringClass(); |
| 28 | + Field field = Lookup.class.getDeclaredField("IMPL_LOOKUP"); |
| 29 | + field.setAccessible(true); |
| 30 | + Lookup lookup = (Lookup) field.get(null); |
| 31 | + |
| 32 | + this.unboundHandle = lookup.unreflectSpecial(defaultMethod, declaringClass); |
| 33 | + } catch (NoSuchFieldException ex) { |
| 34 | + throw new IllegalStateException(ex); |
| 35 | + } catch (IllegalAccessException ex) { |
| 36 | + throw new IllegalStateException(ex); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Bind this handler to a proxy object. After bound, DefaultMethodHandler#invoke will act as if it was called |
| 42 | + * on the proxy object. Must be called once and only once for a given instance of DefaultMethodHandler |
| 43 | + */ |
| 44 | + public void bindTo(Object proxy) { |
| 45 | + if(handle != null) { |
| 46 | + throw new IllegalStateException("Attempted to rebind a default method handler that was already bound"); |
| 47 | + } |
| 48 | + handle = unboundHandle.bindTo(proxy); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Invoke this method. DefaultMethodHandler#bindTo must be called before the first |
| 53 | + * time invoke is called. |
| 54 | + */ |
| 55 | + @Override |
| 56 | + public Object invoke(Object[] argv) throws Throwable { |
| 57 | + if(handle == null) { |
| 58 | + throw new IllegalStateException("Default method handler invoked before proxy has been bound."); |
| 59 | + } |
| 60 | + return handle.invokeWithArguments(argv); |
| 61 | + } |
| 62 | +} |
0 commit comments