本文介绍了静态块未在JDK 7中执行,“未找到主方法”,但在JDK 1.5中有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个带有一个静态块的简单类

I have written a simple class with one static block

class Hello
{

  static {
           System.out.println("Hello");
       System.exit(0);
     }
}

当我使用jdk1.5运行它时,静态块正在执行

When i am running it using jdk1.5, static block is getting executed

C:\apps\Java\jdk1.5.0_21\bin>javac Hello.java

C:\apps\Java\jdk1.5.0_21\bin>
C:\apps\Java\jdk1.5.0_21\bin>
C:\apps\Java\jdk1.5.0_21\bin>
C:\apps\Java\jdk1.5.0_21\bin>java Hello

Hello

但是当我使用jdk1.7运行它时,我收到以下错误

But when i am running it using jdk1.7, i am getting following error

C:\Program Files (x86)\Java\jdk1.7.0_02\bin>
C:\Program Files (x86)\Java\jdk1.7.0_02\bin>javac Hello.java

C:\Program Files (x86)\Java\jdk1.7.0_02\bin>java Hello
Error: Main method not found in class Hello, please define the main method as:
    public static void main(String[] args)

任何人都可以对JDK 5和JDK 7中的这种行为改变有所了解吗?

Can anyone have any idea about this change of behaviour in JDK 5 and JDK 7?

提前致谢!!

推荐答案

Java 7在加载前查找main方法班级。这是以前java版本的行为更改,因此您的静态块未执行。 在以前的版本中,行为是JRE用于在加载类后以及执行静态块后查找main方法。

Java 7 looks for a main method before loading the class. This is a behavior change from previous java versions and hence your static block is not executing. In previous versions, the behavior was that JRE used to look for main method post loading the class and after executing the static blocks.

这篇关于静态块未在JDK 7中执行,“未找到主方法”,但在JDK 1.5中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 16:31