Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to notate type argument for generically polymorphic static method in jshell?

Tags:

java

jshell

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.

like image 581
d8d0d65b3f7cf42 Avatar asked Jun 06 '16 22:06

d8d0d65b3f7cf42


Video Answer


1 Answers

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.

like image 76
Steffen Harbich Avatar answered Nov 15 '22 20:11

Steffen Harbich