开发者

Having another static method as the entry point of the java program?

As we all know Java pr开发者_运维百科ogram will start executing from the public static void main(String[] args) method of the class.

So was curious to know that is there any other way by which we can make another static method as the entry point, that is can we override this property of the JVM to start with some other method than main?


AFAIK the JVM always starts with the main method. The only official reference I was able to find is in section 12.1.4 of the java language specifications, which states:

12.1.4 Invoke Test.main

Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

The method main must be declared public, static, and void. It must accept a single argument that is an array of strings.

That doesn't seem like an awful restriction to me, though. You could technically write a "MainSelector" class whose main() takes the fully qualified name of a class and method as a command line argument, and uses reflection to invoke that method.


It is "possible" but it depends on the implementation.

Quote from the JVM Specification:

The Java virtual machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (§5.3.1). The Java virtual machine then links the initial class, initializes it, and invokes its public class method void main(String[]). The invocation of this method drives all further execution. Execution of the Java virtual machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.

In some implementations of the Java virtual machine the initial class could be provided as a command line argument, as in JDK releases 1.0 and 1.1. Alternatively, the initial class could be provided by the implementation. In this case the initial class might set up a class loader that would in turn load an application, as in the Java 2 SDK, Standard Edition, v1.2. Other choices of the initial class are possible so long as they are consistent with the specification given in the previous paragraph.

Java 1.6 VM for windows doesn't provide this functionality.


You can always write your own JVM (or take a open source version and change it slightly). But it probably would be a JVM with a bug. At least I assume that the behavior of starting the main method is devined in the specification of the JVM/Java Language somewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜