对数组 clone() 的方法引用导致 NoClassDefFoundError: Array
2022-09-04 21:52:44
当我运行此代码时
List<int[]> list = Arrays.asList(new int[]{1, 2, 3}, new int[]{4, 5});
int[][] arr = list.stream().map(j -> j.clone()).toArray(int[][]::new);
System.out.println(Arrays.deepToString(arr));
它按预期工作,我得到输出
[[1, 2, 3], [4, 5]]
但是,如果我将 lambda 替换为clone()
int[][] arr = list.stream().map(int[]::clone).toArray(int[][]::new);
我得到一个运行时异常:
Exception in thread "main" java.lang.NoClassDefFoundError: Array
at Main.lambda$MR$main$clone$8ed4b78b$1(Main.java:14)
at Main$$Lambda$1/1160460865.apply(Unknown Source)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:576)
at java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:255)
at java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:438)
at Main.main(Main.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.ClassNotFoundException: Array
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
我完全不明白这一点。我本来以为方法参考和 lambda 是等价的。这似乎也是一个非常奇怪的例外。谁能解释一下?
我使用的是 JDK 1.8.0_25。