Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Package Name as a Constant (See related posts)

getClass().getPackage().getName() is not a reliable solution, because getPackage() can be null depending on a class loader.
static final String PACKAGE_NAME = MyClass.class.getName().substring(0, 
            MyClass.class.getName().lastIndexOf('.'));

Comments on this post

pediddle posts on Apr 04, 2007 at 16:46
Just a note, it's a constant but not a **compile time** constant, which means you lose a lot of optimizations about it. I am a fan of the ".class" syntax to be guaranteed to get a value. Also note that if you're dealing with classloaders, there might actually be more than one instance of the MyClass class floating around.

Sometimes I hate Java.
ejboy posts on Apr 05, 2007 at 14:59
1) It's initialized only once during class initialization, so I don't see a big problem being a "runtime constant"
2) I don't see any problems with different class floating around, because this snippet stores the package name which is obviously the same.

Anyway, it would be great if somebody provide a better solution
DRMacIver posts on Apr 05, 2007 at 18:41
Why exactly do you want the package name as a constant?

The most common need for dealing with class and package names as literal strings is for loading resources from the classpath. I avoid this by making sure there's a marker class I can use in the package I'm loading the resource from and loading relative to that class.

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts