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).