Java Reference
In-Depth Information
Solution
Use getClass() or getClassLoader() and either getResource() or getRe-
sourceAsStream() .
Discussion
There are three varieties of getResource() methods, some of which exist (with the exact
same signature) both in the Class class (see Chapter 23 ) and in the ClassLoader class (see
Constructing a Class from Scratch with a ClassLoader ). The methods in Class delegate to
the ClassLoader , so there is little difference between them. The methods are summarized in
Table 10-4 .
Table 10-4. The getResource* methods
Method signature
In Class In ClassLoader
Y
Y
public InputStream getResourceAsStream(String);
Y
Y
public URL getResource(String);
public Enumeration<URL> getResources(String) throws IOException; N
Y
The first is designed to quickly and easily locate a “resource” or file on your classpath. Using
the Class version, or the other one with a standard classloader implementation, the resource
can be a physical file, or a file inside a JAR file. If you define your own classloader, your
imagination is the limit, as long as it can be represented as an InputStream . This is com-
monly used as:
InputStream is = getClass (). getResourceAsStream ( "foo.properties" );
// then do something with the InputStream...
The second form returns a URL , which again, can be interpreted in various ways (see the dis-
cussion of reading from a URL in REST Web Service Client ).
The third form, only usable with a ClassLoader instance, returns an Enumeration of URL
objects. This is intended to return all the resources that match a given string; remember that a
CLASSPATH can consist of pretty much any number of directories and/or JAR files, so this
Search WWH ::




Custom Search