Java Reference
In-Depth Information
invoked; or a non-final static field of the class being accessed. This in-
cludes the use of reflection methods to perform those actions. Addition-
ally, before an assert statement is executed inside a nested type, the
enclosing top-level class (if there is one) must be initialized. Using re-
flection to directly load a class may also trigger initializationsuch as use
of Class.forName(name) but note that simple use of a class literal does not
trigger initialization.
16.13.3. Loading Related Resources
Classes are the primary resources a program needs, but some classes
need other associated resources, such as text, images, or sounds. Class
loaders have ways to find class resources, and they can use the same
mechanisms to get arbitrary resources stored with the class. In our
game example, a particular playing strategy might have an associated
"book" that tells it how to respond to particular situations. The following
code, in a BoldPlayer class, would get an InputStream for such a book:
String book = "BoldPlayer.book";
InputStream in;
ClassLoader loader = this.getClass().getClassLoader();
if (loader != null)
in = loader.getResourceAsStream(book);
else
in = ClassLoader.getSystemResourceAsStream(book);
System resources are associated with system classes (the classes that
may have no associated class loader instance). The static ClassLoader
method getSystemResourceAsStream returns an InputStream for a named re-
source. The preceding code checks to see whether it has a class loader.
If it does not, the class has been loaded by the bootstrap class loader;
otherwise, it uses the class loader's getresourceAsStream method to turn
its resource name into a byte input stream. The resource methods re-
turn null if the resource is not found.
 
Search WWH ::




Custom Search