How to execute a specific function before main () in C and JAVA?

I want to execute one function before the main function in C and JAVA. I know one way that using the #pragma in C. Is there another way to do this in both languages?

+4
source share
6 answers

I can imagine two simple (-ish) ways to do this in Java:

Method # 1 - Static Initializers

For instance:

 public class Test { static { System.err.println("Static initializer first"); } public static void main(String[] args) { System.err.println("In main"); } } 

Method # 2 is the main proxy.

 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. } } 

Then you run this as:

 java <jvm-options> ... ProxyMain <real-Main> arg ... 

There is also a third method, but this requires some “extreme measures”. Basically, you have to create your own JVM launcher that uses a different scheme to run the application. Ask this to do unnecessary things before loading the entry point class and calling its main method. (Or do something completely different.)

You can even replace the default class loader; e.g. How to change the default class loader in Java?

+6
source

in java you can use static block

 public class JavaApplication2 { static { System.out.println("in static "); } public static void main(String[] args) { System.out.println("in main "); } } 
+4
source

Try combining a static block and a static method containing what you want to execute before your main method.

 package test; public class Main { static { beforeMain(); } public static void main(String[] args) { System.out.println("after"); } private static void beforeMain() { System.out.println("before"); } } 

Output:

 before after 
+1
source

As an extension to the C standard, gcc provides a constructor function attribute that allows functions to be called up to main() .

See here for more details (scroll down). Also this SO question and its answers will help with this.

+1
source

This may be the first thing you call from your main function. This way it will work up to your “real” core function.

0
source

Use this method (what you want to run before the main method) as the main method.

Then it's that simple

Or use the static block before main()

0
source

Source: https://habr.com/ru/post/1488440/


All Articles