File: DefaultMethods.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (386 lines) | stat: -rw-r--r-- 16,408 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
 * Copyright (c) 2020, 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.
 */

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

/**
 * @test
 * @bug 8159746
 * @run testng DefaultMethods
 * @summary Basic tests for Proxy::invokeSuper default method
 */

public class DefaultMethods {
    public interface I1 {
        default int m() {
            return 10;
        }
    }

    public interface I2 {
        default int m() {
            return 20;
        }

        private void privateMethod() {
            throw new Error("should not reach here");
        }
    }

    // I3::m inherits from I2:m
    public interface I3 extends I2 {
        default int m3(String... s) {
            return Arrays.stream(s).mapToInt(String::length).sum();
        }
    }

    public interface I4 extends I1, I2 {
        default int m() {
            return 40;
        }

        default int mix(int a, String b) {
            return 0;
        }
    }

    public interface I12 extends I1, I2 {
        @Override
        int m();

        default int sum(int a, int b) {
            return a + b;
        }

        default Object[] concat(Object first, Object... rest) {
            Object[] result = new Object[1 + rest.length];
            result[0] = first;
            System.arraycopy(rest, 0, result, 1, rest.length);
            return result;
        }
    }

    public interface IX {
        default void doThrow(Throwable exception) throws Throwable {
            throw exception;
        }
    }

    private static Method findDefaultMethod(Class<?> refc, Method m) {
        try {
            assertTrue(refc.isInterface());

            Method method = refc.getMethod(m.getName(), m.getParameterTypes());
            assertTrue(method.isDefault());
            return method;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void test() {
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        Object proxy = Proxy.newProxyInstance(loader, new Class<?>[] { I1.class, I2.class},
                (o, method, params) -> {
                    return InvocationHandler.invokeDefault(o, findDefaultMethod(I2.class, method), params);
                });
        I1 i1 = (I1) proxy;
        assertEquals(i1.m(), 20);
    }

    // a default method is declared in one of the proxy interfaces
    @DataProvider(name = "defaultMethods")
    private Object[][] defaultMethods() {
        return new Object[][]{
            new Object[]{new Class<?>[]{I1.class, I2.class}, true, 10},
            new Object[]{new Class<?>[]{I1.class, I3.class}, true, 10},
            new Object[]{new Class<?>[]{I1.class, I12.class}, true, 10},
            new Object[]{new Class<?>[]{I2.class, I12.class}, true, 20},
            new Object[]{new Class<?>[]{I4.class}, true, 40},
            new Object[]{new Class<?>[]{I4.class, I3.class}, true, 40},
            new Object[]{new Class<?>[]{I12.class}, false, -1},
            new Object[]{new Class<?>[]{I12.class, I1.class, I2.class}, false, -1}
        };
    }

    @Test(dataProvider = "defaultMethods")
    public void testDefaultMethod(Class<?>[] intfs, boolean isDefault, int expected) throws Throwable {
        InvocationHandler ih = (proxy, method, params) -> {
            System.out.format("invoking %s with parameters: %s%n", method, Arrays.toString(params));
            switch (method.getName()) {
                case "m":
                    assertTrue(method.isDefault() == isDefault);
                    assertTrue(Arrays.stream(proxy.getClass().getInterfaces())
                                     .anyMatch(intf -> method.getDeclaringClass() == intf),
                               Arrays.toString(proxy.getClass().getInterfaces()));
                    if (method.isDefault()) {
                        return InvocationHandler.invokeDefault(proxy, method, params);
                    } else {
                        return -1;
                    }
                default:
                    throw new UnsupportedOperationException(method.toString());
            }
        };

        Object proxy = Proxy.newProxyInstance(DefaultMethods.class.getClassLoader(), intfs, ih);
        Method m = proxy.getClass().getMethod("m");
        int result = (int)m.invoke(proxy);
        assertEquals(result, expected);
    }

    // a default method may be declared in a proxy interface or
    // inherited from a superinterface of a proxy interface
    @DataProvider(name = "supers")
    private Object[][] supers() {
        return new Object[][]{
            // invoke "m" implemented in the first proxy interface
            // same as the method passed to InvocationHandler::invoke
            new Object[]{new Class<?>[]{I1.class}, I1.class, 10},
            new Object[]{new Class<?>[]{I2.class}, I2.class, 20},
            new Object[]{new Class<?>[]{I1.class, I2.class}, I1.class, 10},
            // "m" is implemented in I2, an indirect superinterface of I3
            new Object[]{new Class<?>[]{I3.class}, I3.class, 20},
            // "m" is implemented in I1, I2 and overridden in I4
            new Object[]{new Class<?>[]{I4.class}, I4.class, 40},
            // invoke "m" implemented in the second proxy interface
            // different from the method passed to InvocationHandler::invoke
            new Object[]{new Class<?>[]{I1.class, I2.class}, I2.class, 20},
            new Object[]{new Class<?>[]{I1.class, I3.class}, I3.class, 20},
            // I2::m is implemented in more than one proxy interface directly or indirectly
            // I3::m resolves to I2::m (indirect superinterface)
            // I2 is the superinterface of I4 and I4 overrides m
            // the proxy class can invoke I4::m and I2::m
            new Object[]{new Class<?>[]{I3.class, I4.class}, I3.class, 20},
            new Object[]{new Class<?>[]{I3.class, I4.class}, I4.class, 40},
            new Object[]{new Class<?>[]{I4.class, I3.class}, I3.class, 20},
            new Object[]{new Class<?>[]{I4.class, I3.class}, I4.class, 40}
        };
    }

    @Test(dataProvider = "supers")
    public void testSuper(Class<?>[] intfs, Class<?> proxyInterface, int expected) throws Throwable {
        final InvocationHandler ih = (proxy, method, params) -> {
            switch (method.getName()) {
                case "m":
                    assertTrue(method.isDefault());
                    return InvocationHandler.invokeDefault(proxy, findDefaultMethod(proxyInterface, method), params);
                default:
                    throw new UnsupportedOperationException(method.toString());
            }
        };
        ClassLoader loader = proxyInterface.getClassLoader();
        Object proxy = Proxy.newProxyInstance(loader, intfs, ih);
        if (proxyInterface == I1.class) {
            I1 i1 = (I1) proxy;
            assertEquals(i1.m(), expected);
        } else if (proxyInterface == I2.class) {
            I2 i2 = (I2) proxy;
            assertEquals(i2.m(), expected);
        } else if (proxyInterface == I3.class) {
            I3 i3 = (I3) proxy;
            assertEquals(i3.m(), expected);
        } else if (proxyInterface == I4.class) {
            I4 i4 = (I4) proxy;
            assertEquals(i4.m(), expected);
        } else {
            throw new UnsupportedOperationException(proxyInterface.toString());
        }
        // invoke via InvocationHandler.invokeDefaultMethod directly
        assertEquals(InvocationHandler.invokeDefault(proxy, proxyInterface.getMethod("m")), expected);
    }

    // invoke I12 default methods with parameters and var args
    @Test
    public void testI12() throws Throwable {
        final InvocationHandler ih = (proxy, method, params) -> {
            System.out.format("invoking %s with parameters: %s%n", method, Arrays.toString(params));
            switch (method.getName()) {
                case "sum":
                case "concat":
                    assertTrue(method.isDefault());
                    return InvocationHandler.invokeDefault(proxy, method, params);
                default:
                    throw new UnsupportedOperationException(method.toString());
            }
        };
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        I12 i12 = (I12) Proxy.newProxyInstance(loader, new Class<?>[] { I12.class }, ih);
        assertEquals(i12.sum(1, 2), 3);
        assertEquals(i12.concat(1, 2, 3, 4), new Object[]{1, 2, 3, 4});
        Method m = I12.class.getMethod("concat", Object.class, Object[].class);
        assertTrue(m.isDefault());
        assertEquals(InvocationHandler.invokeDefault(i12, m, 100, new Object[] {"foo", true, "bar"}),
                     new Object[] {100, "foo", true, "bar"});
    }

    // test a no-arg default method with and without arguments passed in the invocation
    @Test
    public void testEmptyArgument() throws Throwable {
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        Object proxy = Proxy.newProxyInstance(loader, new Class<?>[]{I4.class}, HANDLER);
        Method m1 = I4.class.getMethod("m");
        assertTrue(m1.getDeclaringClass() == I4.class);
        assertTrue(m1.isDefault());
        InvocationHandler.invokeDefault(proxy, m1);
        InvocationHandler.invokeDefault(proxy, m1, new Object[0]);

        Method m2 = I4.class.getMethod("mix", int.class, String.class);
        assertTrue(m1.getDeclaringClass() == I4.class);
        assertTrue(m1.isDefault());
        InvocationHandler.invokeDefault(proxy, m2, Integer.valueOf(100), "foo");
    }

    @Test
    public void testVarArgs() throws Throwable {
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        I3 proxy = (I3)Proxy.newProxyInstance(loader, new Class<?>[]{I3.class}, HANDLER);
        Method m = I3.class.getMethod("m3", String[].class);
        assertTrue(m.isVarArgs() && m.isDefault());
        assertEquals(proxy.m3("a", "b", "cde"), 5);
        assertEquals(InvocationHandler.invokeDefault(proxy, m, (Object)new String[] { "a", "bc" }), 3);
    }

    /*
     * Invoke I12::m which is an abstract method
     */
    @Test(expectedExceptions = {IllegalArgumentException.class})
    public void invokeAbstractMethod() throws Exception {
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        I12 proxy = (I12) Proxy.newProxyInstance(loader, new Class<?>[]{I12.class}, HANDLER);
        Method method = I12.class.getMethod("m");
        assertTrue(method.getDeclaringClass() == I12.class);
        assertFalse(method.isDefault());
        proxy.m();
    }

    /*
     * Invoke a non proxy (default) method with parameters
     */
    @Test(expectedExceptions = {IllegalArgumentException.class})
    public void invokeNonProxyMethod() throws Throwable {
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        I3 proxy = (I3) Proxy.newProxyInstance(loader, new Class<?>[]{I3.class}, HANDLER);
        Method m = I4.class.getMethod("mix", int.class, String.class);
        assertTrue(m.isDefault());
        InvocationHandler.invokeDefault(proxy, m);
    }

    // negative cases
    @DataProvider(name = "negativeCases")
    private Object[][] negativeCases() {
        return new Object[][]{
            // I4::m overrides I1::m and I2::m
            new Object[] { new Class<?>[]{I4.class}, I1.class, "m" },
            new Object[] { new Class<?>[]{I4.class}, I2.class, "m" },
            // I12::m is not a default method
            new Object[] { new Class<?>[]{I12.class}, I12.class, "m" },
            // non-proxy default method
            new Object[] { new Class<?>[]{I3.class}, I1.class, "m" },
            // not a default method and not a proxy interface
            new Object[] { new Class<?>[]{I12.class}, DefaultMethods.class, "test" },
            new Object[] { new Class<?>[]{I12.class}, Runnable.class, "run" },
            // I2::privateMethod is a private method
            new Object[] { new Class<?>[]{I3.class}, I2.class, "privateMethod" }
        };
    }

    @Test(dataProvider = "negativeCases", expectedExceptions = {IllegalArgumentException.class})
    public void testNegativeCase(Class<?>[] interfaces, Class<?> defc, String name)
            throws Throwable {
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        Object proxy = Proxy.newProxyInstance(loader, interfaces, HANDLER);
        try {
            Method method = defc.getDeclaredMethod(name);
            InvocationHandler.invokeDefault(proxy, method);
        } catch (Throwable e) {
            System.out.format("%s method %s::%s exception thrown: %s%n",
                              Arrays.toString(interfaces), defc.getName(), name, e.getMessage());
            throw e;
        }
    }

    @DataProvider(name = "illegalArguments")
    private Object[][] illegalArguments() {
        return new Object[][] {
            new Object[] { new Object[0]},
            new Object[] { new Object[] { 100 }},
            new Object[] { new Object[] { 100, "foo", 100 }},
            new Object[] { new Object[] { 100L, "foo" }},
            new Object[] { new Object[] { "foo", 100 }},
            new Object[] { new Object[] { null, "foo" }}
        };
    }

    @Test(dataProvider = "illegalArguments", expectedExceptions = {IllegalArgumentException.class})
    public void testIllegalArgument(Object[] args) throws Throwable {
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        I4 proxy = (I4)Proxy.newProxyInstance(loader, new Class<?>[]{I4.class}, HANDLER);
        Method m = I4.class.getMethod("mix", int.class, String.class);
        assertTrue(m.isDefault());
        if (args.length == 0) {
            // substitute empty args with null since @DataProvider doesn't allow null array
            args = null;
        }
        InvocationHandler.invokeDefault(proxy, m, args);
    }

    @DataProvider(name = "throwables")
    private Object[][] throwables() {
        return new Object[][] {
            new Object[] { new IOException() },
            new Object[] { new IllegalArgumentException() },
            new Object[] { new ClassCastException() },
            new Object[] { new NullPointerException() },
            new Object[] { new AssertionError() },
            new Object[] { new Throwable() }
        };
    }

    @Test(dataProvider = "throwables")
    public void testInvocationException(Throwable exception) throws Throwable {
        ClassLoader loader = DefaultMethods.class.getClassLoader();
        IX proxy = (IX)Proxy.newProxyInstance(loader, new Class<?>[]{IX.class}, HANDLER);
        Method m = IX.class.getMethod("doThrow", Throwable.class);
        try {
            InvocationHandler.invokeDefault(proxy, m, exception);
        } catch (Throwable e) {
            assertEquals(e, exception);
        }
    }

    private static final InvocationHandler HANDLER = (proxy, method, params) -> {
        System.out.format("invoking %s with parameters: %s%n", method, Arrays.toString(params));
        return InvocationHandler.invokeDefault(proxy, method, params);
    };
}