Java Reference
In-Depth Information
Custom classloader
When performing classloading, sooner or later we have to turn data into code. As
noted earlier, the defineClass() (actually a group of related methods) is responsi‐
ble for converting a byte[] into a class object.
This method is usually called from a subclass—for example, this simple custom
classloader that creates a class object from a file on disk:
public static class DiskLoader extends ClassLoader {
public DiskLoader () {
super ( DiskLoader . class . getClassLoader ());
}
public Class <?> loadFromDisk ( String clzName ) throws IOException {
byte [] b = Files . readAllBytes ( Paths . get ( clzName ));
return defineClass ( null , b , 0 , b . length );
}
}
Notice that in the preceding example we didn't need to have the class file in the
“correct” location on disk, as we did for the URLClassLoader example.
We need to provide a classloader to act as parent for any custom classloader. In this
example, we provided the classloader that loaded the DiskLoader class (which
would usually be the application classloader).
Custom classloading is a very common technique in Java EE and advanced SE envi‐
ronments, and it provides very sophisticated capabilities to the Java platform. We'll
see an example of custom classloading later on in this chapter.
One drawback of dynamic classloading is that when working with a class object that
we loaded dynamically, we typically have little or no information about the class. To
work effectively with this class, we will therefore usually have to use a set of
dynamic programming techniques known as reflection.
Relection
Reflection is the capability of examining, operating on, and modifying objects at
runtime. This includes modifying their structure and behavior—even self-
modification.
Reflection is capable of working even when type and method names are not known
at compile time. It uses the essential metadata provided by class objects, and can dis‐
cover method or field names from the class object—and then acquire an object rep‐
resenting the method or field.
Instances can also be constructed reflexively (by using Class::newInstance() or
another constructor). With a reflexively constructed object, and a Method object, we
can then call any method on an object of a previously unknown type.
Search WWH ::




Custom Search