In one of the Spring classes, org.springframework.web.servlet.view.tiles2.TilesConfigurer, the following code is run:
Class clazz = getClass().getClassLoader().loadClass(
"org.apache.tiles.extras.complete.CompleteAutoloadTilesInitializer");
this.tilesInitializer = (TilesInitializer) clazz.newInstance();
Why didn't the author just write
this.tilesInitializer = new org.apache.tiles.extras
.complete.CompleteAutoloadTilesInitializer()
Is there a difference in the output or an improvement to doing it the first way?
Update The code in the TilesConfigurer class is exactly as in the first example. It is not loading the string out of a DI layer. It's a hard coded string.
In the second case the dependency exists in the code (at compile time), while in the first case the dependency is only created when this code is run.
Doing things the first way can be useful for a couple of reasons:
You want to speed up program loading (in the second case the classloader will load the Apache tiles class and its dependencies when this spring class is loaded, in the first case it will wait to do so until this spring code is called)
You want to have code that can stand alone without this dependency (in the second case you cannot compile or load the code without the tiles.extras.... class files present, but in the first case you can, and they might just give some extra functionality if present).
It would be really helpfull if you included the declaration of "tilesInitializer". Most likely it is declared as an interface type.
Loading the actual implementation this way frees you from the compile time dependency - you do not actually need to have the implementing CompleteAutoloadTilesInitializer on your classpath to compile. It also allows you to put the selection of the actual class to be loaded into a configuration file.
Also, at run time it will not produce any UnresolvedClassReference-Exceptions that you can not easily catch/handle because they occur somewhere in the static initialization of classes.
That makes it possible to respond to handle the case where the class is not available in the catch block that surely surrounds the loadClass-call (by selecting a different implementation, or disabling the functionality it provided). This allows users to only deploy the jars they really make use of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With