如何唯一命名一个对象
How to uniquely name an object
我有一个简单的网络应用程序,它从 tomcat JDBC 数据源获取连接。为了跟踪连接使用情况,我计划在打开和关闭连接时实现日志记录。日志应该打印这样的东西。
20151230143623.947[Thread-3] INFO [DataSourceManager:19] Opened connection identified by id : BlahBlahBlah1
20151230143623.947[Thread-3] INFO [DataSourceManager:19] Closed connection identified by id : BlahBlahBlah1
我的打开关闭方法是这样的
Connection openConnection(String JNDILookupName) throws Exception {
Connection connection = DataSourceManager.getConnection(JNDILookupName);
logDBOperation("Opened", connection.toString());
return connection;
}
Connection closeConnection(String JNDILookupName) throws Exception {
connection.close();
logDBOperation("Closed", connection.toString());
}
void logDBOperation(String operation, String connecitonName){
logger.info(operation+" connection identified by id : "+connectionName);
}
这里我使用 connection.toString()
作为连接在日志中的唯一名称。但是我想知道是否有更好的方法来做到这一点。
只需在 Object
超类上使用默认的 toString()
实现。
它已经为您做到了:
getClass().getName() + '@' + Integer.toHexString(hashCode())
toHexString(hashCode())
会在此处为您提供唯一 ID。这是 JVM 保证它将是唯一值。
我有一个简单的网络应用程序,它从 tomcat JDBC 数据源获取连接。为了跟踪连接使用情况,我计划在打开和关闭连接时实现日志记录。日志应该打印这样的东西。
20151230143623.947[Thread-3] INFO [DataSourceManager:19] Opened connection identified by id : BlahBlahBlah1
20151230143623.947[Thread-3] INFO [DataSourceManager:19] Closed connection identified by id : BlahBlahBlah1
我的打开关闭方法是这样的
Connection openConnection(String JNDILookupName) throws Exception {
Connection connection = DataSourceManager.getConnection(JNDILookupName);
logDBOperation("Opened", connection.toString());
return connection;
}
Connection closeConnection(String JNDILookupName) throws Exception {
connection.close();
logDBOperation("Closed", connection.toString());
}
void logDBOperation(String operation, String connecitonName){
logger.info(operation+" connection identified by id : "+connectionName);
}
这里我使用 connection.toString()
作为连接在日志中的唯一名称。但是我想知道是否有更好的方法来做到这一点。
只需在 Object
超类上使用默认的 toString()
实现。
它已经为您做到了:
getClass().getName() + '@' + Integer.toHexString(hashCode())
toHexString(hashCode())
会在此处为您提供唯一 ID。这是 JVM 保证它将是唯一值。