I try to use getClass().getPackage().getName() to get the package name of an object to insert into a log message.
Sometimes it works, at other times it throws a NullPointerException.
Does anyone have any insight into the conditions under which getPackage() returns null ('cause that's what's happening)?
The classes in question are inside a package (as all classes should be).
In this test the call returns the package name as expected.
package wtg.test;
import java.util.*;
public class MapTest {
public MapTest() {
super();
}
public static void main(String[] args) {
System.out.println(new HashMapTest().getClass().getPackage().getName());
}
}
This code does not
package suncertify.db;
import java.rmi.RemoteException;
import java.util.*;
import java.util.logging.Logger;
public class LockManager {
// lots of other methods and declarations
public long lock(int recordId) throws RemoteException {
Logger.getLogger(getClass().getPackage().getName()).entering(this.
getClass().getName(), "lock");
synchronized (locks) {
while (locks.containsKey(recordId)) {
try {
locks.wait();
} catch (InterruptedException ex) {
Logger.getLogger(getClass().getPackage().getName()).
info(
"InterruptedException while waiting for lock to be released");
}
}
long cookie = System.nanoTime();
locks.put(recordId, cookie);
timestamps.put(recordId, new Date());
Logger.getLogger(getClass().getPackage().getName()).exiting(this.
getClass().getName(), "lock");
return cookie;
}
}
// more methods
}