Java Reference
In-Depth Information
String current = new File ( "." ). getCanonicalPath ();
try ( URLClassLoader ulr =
new URLClassLoader ( new URL [] { new URL ( "file://" + current + "/" )})) {
Class <?> clz = ulr . loadClass ( "com.example.DFACaller" );
System . out . println ( clz . getName ());
}
The argument to loadClass() is the binary name of the class file. Note that in order
for the URLClassLoader to find the classes correctly, they need to be in the expected
place on the filesystem. In this example, the class com.example.DFACaller would
need to be found in a file com/example/DFACaller.class relative to the working
directory.
Alternatively, Class provides Class.forName() , a static method that can load
classes that are present on the classpath but that haven't been referred to yet.
This method takes a fully qualified class name. For example:
Class <?> jdbcClz = Class . forName ( "oracle.jdbc.driver.OracleDriver" );
It throws a ClassNotFoundException if class can't be found. As the example indi‐
cates, this was commonly used in older versions of JDBC to ensure that the correct
driver was loaded, while avoiding a direct import dependency on the driver classes.
With the advent of JDBC 4.0, this initialization step is no longer required.
Class.forName() has an alternative, three-argument form, which is sometimes
used in conjunction with alternative class loaders:
Class . forName ( String name , boolean inited , Classloader classloader );
There are a host of subclasses of ClassLoader that deal with individual special cases
of classloading—which fit into the classloader hierarchy.
Classloader Hierarchy
The JVM has a hierarchy of classloaders—each classloader in the system (apart
from the initial, “primordial” classloader) has a parent that they can delegate to.
The convention is that a classloader will ask its parent to resolve and load a class,
and will only perform the job itself if the parent classloader is unable to comply.
Some common classloaders are shown in Figure 11.2 .
Primordial classloader
This is the first classloader to appear in any JVM process, and is only used to load
the core system classes (which are contained in rt.jar ). This classloader does no veri‐
fication, and relies on the boot classpath being secure.
The boot classpath can be affected with the -Xbootclasspath switch—see Chap‐
ter 13 for details.
Search WWH ::




Custom Search