简体   繁体   English

有没有办法在 jshell 中对顶级函数使用方法引用?

[英]Is there a way to use method references for top-level functions in jshell?

Suppose I do this in jshell:假设我在 jshell 中执行此操作:

jshell> void printIsEven(int i) {
   ...>     System.out.println(i % 2 == 0);
   ...> }
|  created method printIsEven(int)

jshell> List<Integer> l = Arrays.asList(7,5,4,8,5,9);
l ==> [7, 5, 4, 8, 5, 9]

jshell> l.forEach(/* ??? */); // is it possible to use a method reference here?

In a normal program I could write l.forEach(this::printIsEven) in a non-static context or l.forEach(MyClass::printIsEven) in the static context of a class named MyClass .在普通程序中,我可以在非静态上下文中编写l.forEach(this::printIsEven)或在名为MyClass的类的静态上下文中l.forEach(MyClass::printIsEven)

Using this::printIsEven in jshell doesn't work because jshell executes statements in a static context, but you can't use a static method reference because there's no class name to prefix ::printIsEven , and trying l.forEach(::printIsEven) is just a syntax error.在 jshell 中使用this::printIsEven不起作用,因为 jshell 在静态上下文中执行语句,但您不能使用静态方法引用,因为没有类名前缀::printIsEven ,并尝试l.forEach(::printIsEven)只是一个语法错误。

You can create a new class for that:您可以为此创建一个新类:

jshell> class Foo { static void printIsEven(int i) {
   ...>     System.out.println(i % 2 == 0);
   ...> }}
|  created class Foo

jshell> Arrays.asList(1,2,3).forEach(Foo::printIsEven)
false
true
false

Technically it is no longer a top-level function, but it achieves the desired effect.从技术上讲,它不再是顶级功能,而是达到了预期的效果。

Now, if you knew that and still want to reference top-level methods...现在,如果您知道这一点并且仍然想引用顶级方法......

As far as I can tell, the "top-level class" that holds "state" for the shell is jdk.jshell.JShell , but jdk.jshell.JShell::printIsEven results in Error: invalid method reference .据我所知,保存外壳“状态”的“顶级类”是jdk.jshell.JShell ,但jdk.jshell.JShell::printIsEven导致Error: invalid method reference And you already mentioned it's not possible to make top-level methods static ( Modifier 'static' not permitted in top-level declarations, ignored ).而且您已经提到不可能使顶级方法成为静态( Modifier 'static' not permitted in top-level declarations, ignored )。

After a quick look at the JEP , it seems intentional.快速浏览JEP 后,似乎是有意为之。 And it actually mentions the "define-static-method-in-new-class" approach from above .它实际上提到了上面的“在新类中定义静态方法”的方法

I'm guessing the top-level "class" needs special magic to be able to redefine methods & other top-level declarations, and the limitations might derive from the JVM's own limitations in its ability to redefine classes/methods at runtime .顶级“类”需要特殊的魔法才能重新定义方法和其他顶级声明,并且这些限制可能源于 JVM 自身在运行时重新定义类/方法的能力的限制。 The source is interesting but I'm not able to derive a meaningful answer from that. 来源很有趣,但我无法从中得出有意义的答案。


Edit: So, I kinda got carried away.编辑:所以,我有点得意忘形了。 This is your fault.这是你的错。
I still think it's not possible to obtain a method reference to a top-level method in jshell, but... my previous guess about the reasons why is probably wrong.我仍然认为不可能在 jshell 中获得对顶级方法的方法引用,但是......我之前对原因的猜测可能是错误的。

The following shows that in jshell, when you "redefine" a class, the old class is still there: the evaluation context just shifts some mappings to resolve further references to the new class definition.下面显示了在 jshell 中,当您“重新定义”一个类时,旧类仍然存在:评估上下文只是移动了一些映射以解析对新类定义的进一步引用。

jshell> class A { static int v=1; void m() { System.out.println(getClass() + " v=" + v); } }
|  created class A

jshell> new A().m()
class REPL.$JShell$11$A v=1

// Changing static value of "v"
jshell> class A { static int v=2; void m() { System.out.println(getClass() + " v=" + v); } }
|  modified class A

// Actually not modified, this is still the same class (and as a result the static init of v has not been reexecuted, so, still 1)
jshell> new A().m()
class REPL.$JShell$11$A v=1

// Let's add a boolean field to change the structure
jshell> class A { static int v=3; boolean x=false; void m() { System.out.println(getClass() + " v=" + v); } }
|  replaced class A

// Notice new class name:
jshell> new A().m()
class REPL.$JShell$11B$A v=3

// But old version is still there, only hidden a bit by evaluation context:
jshell> Class.forName("REPL.$JShell$11$A").getDeclaredField("v").getInt(null)
$7 ==> 1

jshell> Class.forName("REPL.$JShell$11B$A").getDeclaredField("v").getInt(null)
$8 ==> 3

So this little demo suggests it has nothing to do with JVM internals for class redefinition, because no such thing happens here.所以这个小演示表明它与用于类重新定义的 JVM 内部无关,因为这里没有发生这样的事情。

Then I wanted to see the list of all loaded classes:然后我想查看所有加载的类的列表:

jshell> Class c = Thread.currentThread().getContextClassLoader().getClass()
c ==> class jdk.jshell.execution.DefaultLoaderDelegate$RemoteClassLoader

jshell> while (c != java.lang.ClassLoader.class) { c = c.getSuperclass(); System.out.println(c); }
class java.net.URLClassLoader
class java.security.SecureClassLoader
class java.lang.ClassLoader

jshell> c.getDeclaredField("classes").setAccessible(true)
|  java.lang.reflect.InaccessibleObjectException thrown: Unable to make field private final java.util.Vector java.lang.ClassLoader.classes accessible: module java.base does not "opens java.lang" to unnamed module @7494e528
|        at AccessibleObject.checkCanSetAccessible (AccessibleObject.java:337)
|        at AccessibleObject.checkCanSetAccessible (AccessibleObject.java:281)
|        at Field.checkCanSetAccessible (Field.java:175)
|        at Field.setAccessible (Field.java:169)
|        at (#26:1)

Ah, yes, Java 9 modules... dammit :)啊,是的,Java 9 模块......该死的 :)

Oh, well, that'll be all for today.哦,好吧,今天就到此为止。

Being thoroughly aware of a risk stating an obvious thing, there's an easier way to refer to top-level function declaration, compared to wrapping them in classes.充分意识到陈述一个明显事情的风险,与将它们包装在类中相比,有一种更简单的方法来引用顶级函数声明。

jshell> void printIsEven(int i) {
...>     System.out.println(i % 2 == 0);
...> }
|  created method printIsEven(int)

jshell> List<Integer> l = Arrays.asList(7,5,4,8,5,9);
l ==> [7, 5, 4, 8, 5, 9]

jshell> l.forEach(i -> printIsEven(i)); // lambdas can refer to top-level declarations

It's not what's been asked, but it's just a handy way to use eg streams APIs.这不是被问到的,但这只是使用例如流 API 的一种方便的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM