我想在 C 和 JAVA 语言的 main 函数之前执行一个函数。
我知道一种方法,即在 C 语言中使用 #pragma
指令。有没有其他方法可以用两种语言做到这一点?
最佳答案
我可以想到两种用 Java 实现的简单(-ish)方法:
方法#1 - 静态初始化器
例如:
public class Test {
static {
System.err.println("Static initializer first");
}
public static void main(String[] args) {
System.err.println("In main");
}
}
方法#2 - 主代理。
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.
}
}
然后您将其启动为:
java <jvm-options> ... ProxyMain <real-Main> arg ...
还有第三种方法,但它需要一些“极端措施”。基本上,您必须创建自己的 JVM 启动器,该启动器使用不同的方案来启动应用程序。在加载入口点类并调用其 main
方法之前让它做一些额外的事情。 (或者做一些完全不同的事情。)
您甚至可以替换默认的类加载器;例如How to change default class loader in Java?
关于java - 如何在 C 和 JAVA 中的 main() 之前执行特定功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17337744/