Prev: 64-bit JNI
Next: Java - GUI - Date time input box
From: Martin Gregorie on 12 Feb 2010 19:52 On Fri, 12 Feb 2010 18:45:32 -0500, Lew wrote: > On 2/12/2010 6:13 PM, Daniel Pitts wrote: >> There is Class.getResource*, but you probably want >> ClassLoader.getResource* >> >> My understanding is that The Class.getResource looks in the same >> package as the class, where ClassLoader.getResource looks relative to >> the class-path roots which it knows about. > > See the link provided by John B. Matthews and the corresponding entry in > the 'ClassLoader' Javadocs. > > The 'Class' version's behavior depends on the presence or absence of a > leading '/' (slash) in the resource path. Without the leading slash, > the resource is found relative the class's package, with the slash it's > to the class path. Thanks to all in this thread. I've made notes, read the docs for the Class and ClassLoader methods and now think I know enough to do what I wanted to do. -- martin@ | Martin Gregorie gregorie. | Essex, UK org |
From: John B. Matthews on 12 Feb 2010 23:37
In article <hl4m2m$jkj$1(a)news.albasani.net>, Lew <noone(a)lewscanon.com> wrote: > Martin Gregorie <martin(a)address-in-sig.invalid> wrote: > >> So the 'absolute path' takes the class's package as its root. Gotcha. > > John B. Matthews wrote: > > Empirically, yes. It's my best interpretation of the getResource() API: > > > > <http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResource(java ..lang.String)> > > I think you have that backwards. > > AIUI, an absolute resource path (starts with '/') is relative to the class > path, and a relative path (doesn't start with '/') is relative to the > "modified_package_name". > > I am citing from the link provided. Plus, when I've run tests, I've observed > behavior consistent with my interpretation. > > The wiggle room comes from > "The rules for searching resources associated with a given class are > implemented by the defining class loader of the class." > > So class loaders can change these rules. You've elucidated a subtle point that I'd overlooked previously: The leading '/' is a convenient notation in Class#getResource(); package names don't have a leading '.' to modify. The corresponding method in ClassLoader returns null when given a leading '/'. -- John B. Matthews trashgod at gmail dot com <http://sites.google.com/site/drjohnbmatthews> |