in plain 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 id
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 don't see how to make the type argument explicit.
jshell> String y = <String>id("foo")
| Error:
| illegal start of expression
| String y = <String>id("foo");
| ^
What is the name of the implied context class?
Where is the (part of the) jshell specification that would allow me to answer this question? http://openjdk.java.net/jeps/222 just mentions a "synthetic class" in "the wrapping". Does not sound like it could be named.
Indeed your link does not specify the exact nature (like name) of the syntetic class that gets your methods as static methods.
I tried to get the class the snippet is executing in with
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 in stack trace.
The easiest way to circumvent it, is to define your method as a static method in an own class:
jshell> class B { static <A> A id(A x) {return x;} }
This allows you to call
jshell> String y = B.<String>id("foo");
and gets the desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With