如何配置JVM来调用自定义方法而不是Main方法? [英] How to configure JVM to call custom method instead of Main method?

查看:47
本文介绍了如何配置JVM来调用自定义方法而不是Main方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道JVM在类执行期间会寻找main()方法.我们可以自定义JVM来执行我们自己的自定义函数,而不是默认执行main方法吗? 如果是,我们该怎么做?

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?

推荐答案

您可以通过实现本地自定义启动器(如此处所述)来实现:

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

但是坦率地说,如果您只是想对入口点使用不同的约定,那是不值得的.一种更简单的方法是使用常规的main方法编写代理"入口点类,让其查找/加载/调用您的真实"入口点.

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.

另一方面,如果您的目标是在调用main方法之前执行一些代码,则一个技巧是将代码放入入口点类的静态初始化程序块中.例如:

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) {
           // ...
       }
   }

将在调用main方法之前打印"Hello world".

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

推测!也可能会识别出隐藏的Java自举类,该类可以查找/加载/调用普通的入口点类.然后,您可以通过在引导类路径中添加修改后的版本来替换它.但是,您将流连忘返.如果弄错了,对隐藏机制的干扰很可能会严重终止.

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.

这篇关于如何配置JVM来调用自定义方法而不是Main方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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