We know that JVM looks for main() method during class execution. Can we customize JVM to execute our own custom function instead of main method by default? if yes, how do we do it?
2 Answers
You can do this by implementing a native custom launcher as described here:
But frankly, it is not worth the effort if you simply want to use a different convention for the entry point. A simpler approach is to write a "proxy" entry point class with a conventional main
method, have that find / load / call your "real" entry point.
On the other hand, if your goal is to execute some code before the main
method gets called, one trick is to put the code into a static initializer block in the entry point class. For example:
public class Entry {
static {
System.out.println("Hello world");
}
public static void main(String[] args) {
// ...
}
}
will print "Hello world" before the main
method is called.
Speculation! It might also be possible identify the hidden Java bootstrapping class that finds / loads / calls the normal entrypoint class. Then you could replace it by adding a modified version to the bootstrap classpath. However, you will be straying into dangerous territory. Interference with hidden mechanisms is liable to end badly if you get it wrong.

- 698,415
- 94
- 811
- 1,216
No. The main(String[])
method is the Java entry point. You can package your application as a jar then you can set the Main-Class
and run it like java -jar myapp.jar
. See also Setting an Application's Entry Point. That being said, any static
initialization blocks will run before main
. But you get an exception if the class specified doesn't have a main
method. The only other exceptions I can think of are Servlets and (the almost dead) Applets.

- 198,278
- 20
- 158
- 249
-
1Even servlet containers have to have a main, it's just not part of your own deployment package. – chrylis -cautiouslyoptimistic- Sep 25 '16 at 02:39
-
@chrylis Web browsers have a main too, so even with applets that statement is true. Just trying to think outside the box on the question. – Elliott Frisch Sep 25 '16 at 18:39
-
@Elliott Frisch: only if the Webbrowser is implemented in Java. Otherwise, there is no reason for it to have a `main` method. – Holger Sep 26 '16 at 13:54
-
@Elliott Frisch: C has no methods at all, hence no “`main` method” either. The name coincidence is irrelevant anyway, as the question is about the JVM’s search for a `main` method in a Java class. Besides that, a web browser can be implemented in any language, it doesn’t have to be C or C++. – Holger Sep 26 '16 at 14:31