DZone 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

Fyodor has posted 14 posts at DZone. View Full User Profile

Package Name As A Constant

04.04.2007
| 1540 views |
  • submit to reddit
        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

Snippets Manager replied on Wed, 2007/02/14 - 2:44pm

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.

Fyodor Kupolov replied on Wed, 2006/12/20 - 11:28am

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

Snippets Manager replied on Sun, 2007/03/18 - 1:59pm

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.