changeset 13521:ece1d281763e

8206955: MethodHandleProxies.asInterfaceInstance does not support default methods Summary: Cache default method handles. Reviewed-by: mchung, plevart
author psandoz
date Tue, 16 Apr 2019 17:37:16 +0000
parents 42474254c74c
children 900e4921e59d
files src/share/classes/java/lang/invoke/MethodHandleProxies.java test/java/lang/invoke/MethodHandlesProxiesTest.java
diffstat 2 files changed, 155 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/src/share/classes/java/lang/invoke/MethodHandleProxies.java	Thu Apr 04 12:14:51 2019 +0530
+++ b/src/share/classes/java/lang/invoke/MethodHandleProxies.java	Tue Apr 16 17:37:16 2019 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,8 @@
 import java.security.PrivilegedAction;
 import sun.invoke.WrapperInstance;
 import java.util.ArrayList;
+import java.util.concurrent.ConcurrentHashMap;
+
 import sun.reflect.CallerSensitive;
 import sun.reflect.Reflection;
 import sun.reflect.misc.ReflectUtil;
@@ -50,8 +52,10 @@
      * A single-method interface is an interface which declares a uniquely named method.
      * When determining the uniquely named method of a single-method interface,
      * the public {@code Object} methods ({@code toString}, {@code equals}, {@code hashCode})
-     * are disregarded.  For example, {@link java.util.Comparator} is a single-method interface,
-     * even though it re-declares the {@code Object.equals} method.
+     * are disregarded as are any default (non-abstract) methods.
+     * For example, {@link java.util.Comparator} is a single-method interface,
+     * even though it re-declares the {@code Object.equals} method and also
+     * declares default methods, such as {@code Comparator.reverse}.
      * <p>
      * The interface must be public.  No additional access checks are performed.
      * <p>
@@ -175,6 +179,8 @@
             checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class));
             vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount());
         }
+        final ConcurrentHashMap<Method, MethodHandle> defaultMethodMap =
+                hasDefaultMethods(intfc) ? new ConcurrentHashMap<>() : null;
         final InvocationHandler ih = new InvocationHandler() {
                 private Object getArg(String name) {
                     if ((Object)name == "getWrapperInstanceTarget")  return target;
@@ -190,6 +196,9 @@
                         return getArg(method.getName());
                     if (isObjectMethod(method))
                         return callObjectMethod(proxy, method, args);
+                    if (isDefaultMethod(method)) {
+                        return callDefaultMethod(defaultMethodMap, proxy, intfc, method, args);
+                    }
                     throw newInternalError("bad proxy method: "+method);
                 }
             };
@@ -319,4 +328,45 @@
         if (uniqueName == null)  return null;
         return methods.toArray(new Method[methods.size()]);
     }
+
+    private static
+    boolean isDefaultMethod(Method m) {
+        return !Modifier.isAbstract(m.getModifiers());
+    }
+
+    private static
+    boolean hasDefaultMethods(Class<?> intfc) {
+        for (Method m : intfc.getMethods()) {
+            if (!isObjectMethod(m) &&
+                !Modifier.isAbstract(m.getModifiers())) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static
+    Object callDefaultMethod(ConcurrentHashMap<Method, MethodHandle> defaultMethodMap,
+                             Object self, Class<?> intfc, Method m, Object[] args) throws Throwable {
+        assert(isDefaultMethod(m) && !isObjectMethod(m)) : m;
+
+        // Lazily compute the associated method handle from the method
+        MethodHandle dmh = defaultMethodMap.computeIfAbsent(m, mk -> {
+            try {
+                // Look up the default method for special invocation thereby
+                // avoiding recursive invocation back to the proxy
+                MethodHandle mh = MethodHandles.Lookup.IMPL_LOOKUP.findSpecial(
+                        intfc, mk.getName(),
+                        MethodType.methodType(mk.getReturnType(), mk.getParameterTypes()),
+                        self.getClass());
+                return mh.asSpreader(Object[].class, mk.getParameterCount());
+            } catch (NoSuchMethodException | IllegalAccessException e) {
+                // The method is known to exist and should be accessible, this
+                // method would not be called unless the invokeinterface to the
+                // default (public) method passed access control checks
+                throw new InternalError(e);
+            }
+        });
+        return dmh.invoke(self, args);
+    }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/invoke/MethodHandlesProxiesTest.java	Tue Apr 16 17:37:16 2019 +0000
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8206955
+ * @run testng/othervm -ea -esa test.java.lang.invoke.MethodHandlesProxiesTest
+ */
+
+package test.java.lang.invoke;
+
+import org.testng.annotations.Test;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandleProxies;
+import java.lang.invoke.MethodHandles;
+
+import static org.testng.Assert.assertEquals;
+
+public class MethodHandlesProxiesTest {
+
+    public interface A {
+    default String a() {
+        return "A";
+    }
+    }
+
+    public interface B {
+    default String b() {
+        return "B";
+    }
+    }
+
+    public interface C extends A, B {
+        String f();
+
+    default String c() {
+        return "C";
+    }
+
+    default String concat() {
+        return a() + b() + c();
+    }
+    }
+
+    public interface Override extends C {
+        String f();
+
+    default String a() {
+        return "OA";
+    }
+
+    default String b() {
+        return "OB";
+    }
+
+    default String c() {
+        return "OC";
+    }
+    }
+
+    @Test
+        public static void testDefaultMethods() throws Throwable {
+        MethodHandle target = MethodHandles.constant(String.class, "F");
+        C proxy = MethodHandleProxies.asInterfaceInstance(C.class, target);
+
+        assertEquals(proxy.f(), "F");
+        assertEquals(proxy.a(), "A");
+        assertEquals(proxy.b(), "B");
+        assertEquals(proxy.c(), "C");
+        assertEquals(proxy.concat(), "ABC");
+    }
+
+    @Test
+        public static void testOverriddenDefaultMethods() throws Throwable {
+        MethodHandle target = MethodHandles.constant(String.class, "F");
+        Override proxy = MethodHandleProxies.asInterfaceInstance(Override.class, target);
+
+        assertEquals(proxy.a(), "OA");
+        assertEquals(proxy.b(), "OB");
+        assertEquals(proxy.c(), "OC");
+    }
+}