我想在C和JAVA语言的main函数之前执行一个函数.我知道一种方法,就是#pragma在C语言中使用指令.在这两种语言中还有其他方法吗?
我可以想到在Java中使用两种简单的(-ish)方法:
例如:
public class Test {
static {
System.err.println("Static initializer first");
}
public static void main(String[] args) {
System.err.println("In main");
}
}
Run Code Online (Sandbox Code Playgroud)
public class ProxyMain {
public static void main(String[] args) {
String classname = args[0];
// Do some other stuff.
// Load the class
// Reflectively find the 'public static void main(String[])' method
// Reflectively invoke it with the rest of the args.
}
}
Run Code Online (Sandbox Code Playgroud)
然后你启动它:
java <jvm-options> ... ProxyMain <real-Main> arg ...
Run Code Online (Sandbox Code Playgroud)
还有第三种方法,但它需要一些"极端措施".基本上,您必须创建自己的JVM启动程序,该启动程序使用不同的方案来启动应用程序.在加载入口点类并调用其main方法之前,请执行此操作.(或者做一些完全不同的事情.)
你甚至可以替换默认的类加载器; 例如,如何在Java中更改默认类加载器?
小智 5
在Java中,您可以使用静态块
public class JavaApplication2 {
static {
System.out.println("in static ");
}
public static void main(String[] args) {
System.out.println("in main ");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7128 次 |
| 最近记录: |