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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
No. The
main(String[])
method is the Java entry point. You can package your application as a jar then you can set theMain-Class
and run it likejava -jar myapp.jar
. See also Setting an Application's Entry Point. That being said, anystatic
initialization blocks will run beforemain
. But you get an exception if the class specified doesn't have amain
method. The only other exceptions I can think of are Servlets and (the almost dead) Applets.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: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.