How to configure JVM to call custom method instead

2019-09-29 17:22发布

We know that JVM looks for main() method during class execution. Can we customize JVM to execute our own custom function instead of main method by default? if yes, how do we do it?

标签: java jvm
2条回答
爷、活的狠高调
2楼-- · 2019-09-29 17:50

No. The main(String[]) method is the Java entry point. You can package your application as a jar then you can set the Main-Class and run it like java -jar myapp.jar. See also Setting an Application's Entry Point. That being said, any static initialization blocks will run before main. But you get an exception if the class specified doesn't have a main method. The only other exceptions I can think of are Servlets and (the almost dead) Applets.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-09-29 17:57

You can do this by implementing a native custom launcher as described here:

But frankly, it is not worth the effort if you simply want to use a different convention for the entry point. A simpler approach is to write a "proxy" entry point class with a conventional main method, have that find / load / call your "real" entry point.

On the other hand, if your goal is to execute some code before the main method gets called, one trick is to put the code into a static initializer block in the entry point class. For example:

   public class Entry {
       static {
           System.out.println("Hello world");
       }

       public static void main(String[] args) {
           // ...
       }
   }

will print "Hello world" before the main method is called.


Speculation! It might also be possible identify the hidden Java bootstrapping class that finds / loads / calls the normal entrypoint class. Then you could replace it by adding a modified version to the bootstrap classpath. However, you will be straying into dangerous territory. Interference with hidden mechanisms is liable to end badly if you get it wrong.

查看更多
登录 后发表回答