gpt4 book ai didi

java - 使用特定类名时 JShell 错误 "unexpected type"

转载 作者:行者123 更新时间:2023-12-01 08:26:50 24 4
gpt4 key购买 nike

我只是在玩 JShell,似乎定义 class Z{}然后定义var z = new Z()不起作用。但使用不同的类名,如 class Xclass A ,确实有效。

当然,我一定遗漏了一些明显的东西......?

|  Welcome to JShell -- Version 14.0.1
| For an introduction type: /help intro

jshell> class X{}
| created class X

jshell> class Z{}
| created class Z

jshell> var x = new X()
x ==> X@26a1ab54
| created variable x : X

jshell> var z = new Z()
| Error:
| unexpected type
| required: class
| found: type parameter Z
| var z = new Z();
| ^

jshell> class A{}
| created class A

jshell> var a = new A()
a ==> A@2ef1e4fa
| created variable a : A

最佳答案

使用 var可能导致具有 non-denotable type 的变量.例如,looking at the return type可能是 String 的表达式或 Integer :

jshell> /set feedback verbose
jshell> var x = true ? "a" : 1
x ==> "a"
| created variable x : Serializable&Comparable<? extends Serializable&Comparable<?>&java.lang.constant.Constable&java.lang.constant.ConstantDesc>&java.lang.constant.Constable&java.lang.constant.ConstantDesc

jshell正在评估您的代码片段,如果是这种情况,它 wraps it in a block of code以便它可以记录此类型以供以后使用。包装片段包括一个名为 Z 的泛型类型参数。 :
        // private static <Z> Z do_itAux() {
// wtype x_ = y;
// @SuppressWarnings("unchecked")
// Z x__ = (Z) x_;
// return x__;

此参数的名称泄漏到正在评估的代码块中,这意味着类的名称被类型参数隐藏。这使得 Z一个特殊情况——其他单字符示例很好。

关于java - 使用特定类名时 JShell 错误 "unexpected type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62102369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com