Java – how to represent the type parameters of general polymorphic static methods in jshell?

In pure Java, I can write

class P {
    static <A> A id (A x) { return x; }
    static int y = P.<Integer>id(8);
    static String bar = P.<String>id("foo");
}

In jshell, I can declare and use IDs

jshell> <A> A id (A x) { return x; }
|  created method id(A)

jshell> int x = id(8)
x ==> 8

jshell> String y = id("foo")
y ==> "foo"

But I can't see how to make type parameters explicit

jshell> String y = <String>id("foo")
|  Error:
|  illegal start of expression
|  String y = <String>id("foo");
|                     ^

What is the name of the implicit context class?

What parts of the jshell specification allow me to answer this question? http://openjdk.java.net/jeps/222 Only a "comprehensive category" is mentioned in "packaging" It doesn't sound like it can be named

Solution

Indeed, your link does not specify the exact nature (such as the name) of the composite class that treats your method as a static method

I tried to get the code snippet to execute the class

jshell> new Exception().printStackTrace()
java.lang.Exception
    at REPL.$JShell$17.do_it$($JShell$17.java:8)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(java.base@9-ea/Native Method)
    at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(java.base@9-ea/NativeMethodAccessorImpl.java:62)
    at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(java.base@9-ea/DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(java.base@9-ea/Method.java:531)
    at jdk.internal.jshell.remote.RemoteAgent.commandLoop(jdk.jshell@9-ea/RemoteAgent.java:124)
    at jdk.internal.jshell.remote.RemoteAgent.main(jdk.jshell@9-ea/RemoteAgent.java:62)

jshell> Thread.currentThread().getStackTrace()[1].toString()
$15 ==> "do_it$(java:18)"

jshell> Thread.currentThread().getStackTrace()[1].getClassName()
$16 ==> ""

But as you can see, the information is not a stack trace

The simplest way to avoid it is to define your own method as a static method:

jshell> class B { static <A> A id(A x) {return x;} }

This allows you to call

jshell> String y = B.<String>id("foo");

And get the desired results

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>