001package ball.lang.reflect;
002/*-
003 * ##########################################################################
004 * Utilities
005 * %%
006 * Copyright (C) 2008 - 2022 Allen D. Ball
007 * %%
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *      http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 * ##########################################################################
020 */
021import java.lang.invoke.MethodHandles;
022import java.lang.reflect.Constructor;
023import java.lang.reflect.InvocationHandler;
024import java.lang.reflect.Method;
025
026import static org.apache.commons.lang3.reflect.MethodUtils.invokeMethod;
027
028/**
029 * Java 8 implementation of
030 * {@link InvocationHandler#invoke(Object,Method,Object[])} to invoke an
031 * interface default method.  Implementation detail of
032 * {@link DefaultInvocationHandler}.
033 *
034 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
035 */
036public interface DefaultInterfaceMethodInvocationHandler extends InvocationHandler {
037
038    /**
039     * This method assumes {@link Method#isDefault() method.isDefault()} and
040     * will invoke {@link Method} directly.
041     *
042     * @param   proxy           The proxy instance.
043     * @param   method          The {@link Method}.
044     * @param   argv            The argument array.
045     *
046     * @return  The value to return from the {@link Method} invocation.
047     *
048     * @throws  Exception       If the {@link Method} cannot be invoked.
049     */
050    @Override
051    default Object invoke(Object proxy, Method method, Object[] argv) throws Throwable {
052        Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class);
053
054        constructor.setAccessible(true);
055
056        Class<?> declarer = method.getDeclaringClass();
057        Object result =
058            constructor.newInstance(declarer)
059            .in(declarer)
060            .unreflectSpecial(method, declarer)
061            .bindTo(proxy)
062            .invokeWithArguments(argv);
063
064        return result;
065    }
066}
067