I am getting error while running Java program without main(),but I used only static block to test whether the program will execute or not without main().Is there any other way to execute Java program without main().
我在没有main()的情况下运行Java程序时遇到错误,但是我只使用静态块来测试程序是否会在没有main()的情况下执行。是否还有其他方法可以在没有main()的情况下执行Java程序。
3 个解决方案
#1
3
Put System.exit(0) just before the end of the static block. You need this in order to terminated the program just before it will start searching for main method.
在静态块结束之前放置System.exit(0)。你需要这个才能在它开始搜索main方法之前终止程序。
This question is already answered - link
这个问题已经回答了 - 链接
#2
0
Yes, you can use static
initializer block , like this :-
是的,您可以使用静态初始化程序块,如下所示: -
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Outputs :-
Hello, World!
Exception in thread "main" java.lang.NoSuchMethodError: main
线程“main”中的异常java.lang.NoSuchMethodError:main
You can avoid the NoSuchmethodError
by simply calling System.exit(0)
immediately after printing the message like :-
您可以通过在打印消息后立即调用System.exit(0)来避免NoSuchmethodError,如: -
static {
System.out.println("Hello, World!");
System.exit(0);
}
#3
0
Please mention which JDK you are using. If you are using JDK 7 then it will not allow you to run without main();
请提及您正在使用的JDK。如果您使用的是JDK 7,那么它将不允许您在没有main()的情况下运行;
If you are using JDK 6 and Below you can do same without error as follows:
如果您使用的是JDK 6及以下版本,则可以执行相同操作而不会出现如下错误:
public class Hello {
static {
System.out.println("Hello, World!");
System.exit(0);
}
}
#1
3
Put System.exit(0) just before the end of the static block. You need this in order to terminated the program just before it will start searching for main method.
在静态块结束之前放置System.exit(0)。你需要这个才能在它开始搜索main方法之前终止程序。
This question is already answered - link
这个问题已经回答了 - 链接
#2
0
Yes, you can use static
initializer block , like this :-
是的,您可以使用静态初始化程序块,如下所示: -
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Outputs :-
Hello, World!
Exception in thread "main" java.lang.NoSuchMethodError: main
线程“main”中的异常java.lang.NoSuchMethodError:main
You can avoid the NoSuchmethodError
by simply calling System.exit(0)
immediately after printing the message like :-
您可以通过在打印消息后立即调用System.exit(0)来避免NoSuchmethodError,如: -
static {
System.out.println("Hello, World!");
System.exit(0);
}
#3
0
Please mention which JDK you are using. If you are using JDK 7 then it will not allow you to run without main();
请提及您正在使用的JDK。如果您使用的是JDK 7,那么它将不允许您在没有main()的情况下运行;
If you are using JDK 6 and Below you can do same without error as follows:
如果您使用的是JDK 6及以下版本,则可以执行相同操作而不会出现如下错误:
public class Hello {
static {
System.out.println("Hello, World!");
System.exit(0);
}
}