我们可以在没有main()方法的情况下执行java程序吗? [英] Can we execute a java program without a main() method?

查看:325
本文介绍了我们可以在没有main()方法的情况下执行java程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的知识,我们无法在没有main方法的情况下执行,因为在运行java程序时。 java虚拟机查找main方法。如果JVM找不到它将显示运行时错误的主方法,则主线程中的异常无法找到主类。

According to my knowledge we cannot execute without a main method because when your running the java program. java Virtual machine look for the main method .if JVM could not find the main method it will show you run time error Exception in thread main could not find the main class.

但我搜索了很多博客,其中一些人说,是的,如果java程序中有静态块,可以通过静态博客完成,类加载器在java调用main()方法之前加载所有静态块!

But I searched for many blogs and some of them are saying, yes it can be done through static blogs if there is a static block in a java program,the class loader loads all static block before java gives call to main() method!.

这是否真的可行,以及这些可用性是什么。

Is it really possible and what will be the usability of these.

推荐答案

现在 - 没有

在Java 7之前:

是,序列如下:


  • jvm loading class

  • 执行静态块

  • 查找main方法并调用它

所以,如果静态块中有代码,那么将被执行。但这样做毫无意义。

So, if there's code in a static block, it will be executed. But there's no point in doing that.

如何测试:

public final class Test {
    static {
        System.out.println("FOO");
    }
}

然后如果你试图运行这个类(任何一个表格)命令行与 java Test 或使用IDE),结果是:

Then if you try to run the class (either form command line with java Test or with an IDE), the result is:


FOO

java.lang.NoSuchMethodError:main

FOO
java.lang.NoSuchMethodError: main

这篇关于我们可以在没有main()方法的情况下执行java程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆