First load the class with the main method, and then manually load the other classes

I am reading Core Java from Cay Horstmann. There is a passage here that I cannot understand:

At startup, the class containing your mainmethod is loaded. It loads all the classes that it needs. Each of the loaded classes loads the classes that it needs, and so on. This can be time consuming for an upsetting user application. You can give users of your program the illusion of a faster start with the next trick. Make sure that the class containing themainmethod does not explicitly reference other classes. First display a splash screen. Then manually force the other classes to be called by calling Class.forName.

Could you give me a small sample code so that I can understand it?

+4
source share
3 answers

The trick mentioned in the quote is basically a way to give the user the illusion that the application loads faster by displaying a splash screen β€œimmediately” after the program is called and only after that starts loading the classes.

Suppose the main class of your application is TheActualApplication . So, if you create a FastSplash class to run your application, the splash screen may appear earlier than when SlowSplash used as the main class.

 public class FastSplasher { public static void main(String[] args) { SplashWindow.splash(Splasher.class.getResource("splash.gif")); SplashWindow.invokeMain("TheActualApplication", args); SplashWindow.disposeSplash(); } } public class SlowSplasher { public static void main(String[] args) { SplashWindow.splash(Splasher.class.getResource("splash.gif")); TheActualApplication.main(args); SplashWindow.disposeSplash(); } } 

The reason the splash screen may happen earlier when using FastSplash is because Java virtual machines today usually have lazy class resolution and thus you won't see much of a difference. If the class resolution is desired, the splash in SlowSplasher will be displayed only after all the classes used in TheActualApplication . In FastSplasher splash screen appears immediately because the TheActualApplication class TheActualApplication loaded dynamically at run time using reflection and cannot be solved statically and thus loaded at startup.

+2
source

I do not know if this statement is valid and useful. According to the tutorial , splash screens may be displayed before the JVM starts with Java 6, so the trick shown in other answers may not be displayed.

+1
source

MyClass and MyClass2 will be loaded after launching the application

 class MyClass { static { System.out.println("MyClass loaded"); } private MyClass2 ref; } class Main { public static void main(String... args) { System.out.println("Starting application..."); Class.forName("MyClass"); } } 
0
source

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


All Articles