为什么Jshell不执行包含Enum字段的方法?



我有一个简单的class。Zelle是一个简单的Enum

public class Main {
public void getZelle (){
System.out.println(Zelle.RED);
}
public static void test(){
System.out.println(Zelle.Empty);
}
public static void main(String[] args) {
System.out.println("HEllo World");
}
}

如果我想用Jshell打开这些方法,我得到以下错误,我不理解:

jshell> Main.getZelle()
|  Error:
|  non-static method getZelle() cannot be referenced from a static context
|  Main.getZelle()
|  ^-----------^
jshell> Main.test()
|  attempted to use class Main which cannot be instantiated or its methods invoked until variable Zelle is declared
jshell> Main.main(new String[0])
|  attempted to use class Main which cannot be instantiated or its methods invoked until variable Zelle is declared 

但是如果我在IDE中运行main()它将打印我的test()方法

public static void main(String[] args) {
test();
}

您正在以静态方式访问非静态方法。您可以通过创建类的对象来调用非静态方法。你的代码看起来像这样:

public class Main {
public void getZelle (){
System.out.println(Zelle.RED);
}
public static void test(){
System.out.println(Zelle.Empty);
}
public static void main(String[] args) {
System.out.println("HEllo World");
Main main=new Main();  // this is the way to create an o object 
main.getZelle(); //this is how you call a non-static method using class reference
main.getTest();

}
}
Main.getZelle()

您正在尝试将方法getZelle()调用为静态方法-它不是-因此错误消息,因为getZelle()不是静态方法。

Main.test()

test()是一个静态方法,但是它引用了Zelle(你声称是一个枚举,但你没有发布它的定义)和JShell不知道如何找到enum,因此错误消息。JShell试图编译你的类Main,但它不能,因为Main引用ZelleJShell找不到Zelle的定义。

Main.main(new String[0])

Main.test()相同的问题。

,因为我找不到Zelle的定义在你的问题,我猜它是什么和它添加到代码,你进入JShell通过编辑器。代码如下:

enum Zelle {
Empty, RED
}
public class Main {
public void getZelle (){
System.out.println(Zelle.RED);
}
public static void test(){
System.out.println(Zelle.Empty);
}
public static void main(String[] args) {
System.out.println("HEllo World");
}
}

现在,当我在JShell中输入Main.main(new String[0])时,代码执行并且我没有得到错误消息。但是,请注意,Main.getZelle()仍然会导致错误,因为getZelle()不是静态方法(如上所述)。

我还建议您采用Java命名约定。Empty应该是EMPTY

你应该声明你的enumZelle并创建Main类的实例来调用非静态方法:

enum Zelle {
RED, Empty
}

final var main = new Main();
main.getZelle();  // RED
Main.test();  // Empty
Main.main(new String[0]); // HEllo World

您需要通过JShell Nameofenum.java将Enum导入JShell。