Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c

pragma

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?

like image 662
New_User Avatar asked Dec 12 '22 13:12

New_User


1 Answers

I can think of two simple(-ish) ways to do it in Java:

Method #1 - static initializers

For example:

public class Test {
    static {
        System.err.println("Static initializer first");
    }

    public static void main(String[] args) {
        System.err.println("In main");
    }
}

Method #2 - A proxy 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?

like image 61
Stephen C Avatar answered Dec 14 '22 23:12

Stephen C