I want to execute one function before main function in C and JAVA language.
I know one way that is, by using #pragma
directive in C language. Is there any other way to do that in both languages?
I can think of two simple(-ish) ways to do it in Java:
For example:
public class Test {
static {
System.err.println("Static initializer first");
}
public static void main(String[] args) {
System.err.println("In main");
}
}
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.
}
}
You then launch this as:
java <jvm-options> ... ProxyMain <real-Main> arg ...
There is also a 3rd method, but it requires some "extreme measures". Basically you have to create your own JVM launcher that uses a different scheme for starting the application. Have this do the extra stuff before loading the entry point class and calling its main
method. (Or do something different entirely.)
You could even replace the default classloader; e.g. How to change default class loader in Java?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With