java执行main方法_如何在没有main()方法的情况下执行Java程序?

java执行main方法

Have you ever thought about executing your java program
without main() method? If you write a program without main() and compile it
then it will compile successfully. But as you execute the program it will show
an error that Main method not found in the class. JVM verify the code before
its execution. JVM checks for main() method and if not found it will show
error.
There is a way to execute your java program without using
main(). This can be done using static block. JVM has four phases as I have
discussed in one of my article about Java Virtual Machine Architecture and Structure.
  • Load Code
  • Verify Code
  • Execute Code
  • Provide Runtime Environment
Static block executed at the loading of code. In below
example we get output and then error is shown because the code is executed at
loading of code and after that JVM verifies the code and show error.
class demo
{
                static
                {
                                System.out.println(“Static
Block”);
                }             
}
Note:  This method will work till Java 6. Java 7 and
newer versions doesn’t allow this because JVM checks presence of main method
before initializing the class .
If you have any other
such trick then you can share it by commenting below.
Have you ever thought about executing your java program
without main() method? If you write a program without main() and compile it
then it will compile successfully. But as you execute the program it will show
an error that Main method not found in the class. JVM verify the code before
its execution. JVM checks for main() method and if not found it will show
error.
There is a way to execute your java program without using
main(). This can be done using static block. JVM has four phases as I have
discussed in one of my article about Java Virtual Machine Architecture and Structure .
  • Load Code
  • Verify Code
  • Execute Code
  • Provide Runtime Environment
Static block executed at the loading of code. In below
example we get output and then error is shown because the code is executed at
loading of code and after that JVM verifies the code and show error.
class demo
{
                static
                {
                                System.out.println(“Static
Block”);
                }             
}
Note:  This method will work till Java 6. Java 7 and
newer versions doesn’t allow this because JVM checks presence of main method
before initializing the class .
If you have any other
such trick then you can share it by commenting below.

翻译自: https://www.thecrazyprogrammer.com/2014/06/how-to-execute-your-java-program-without-main-method.html

java执行main方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值