Java 如何唯一地命名对象
我有一个简单的webapp,它从tomcatjdbc数据源获取连接。为了跟踪连接使用情况,我计划在打开和关闭连接时实现日志记录。日志应该打印这样的东西Java 如何唯一地命名对象,java,jdbc,tomcat7,apache-commons-dbcp,Java,Jdbc,Tomcat7,Apache Commons Dbcp,我有一个简单的webapp,它从tomcatjdbc数据源获取连接。为了跟踪连接使用情况,我计划在打开和关闭连接时实现日志记录。日志应该打印这样的东西 20151230143623.947[Thread-3] INFO [DataSourceManager:19] Opened connection identified by id : BlahBlahBlah1 20151230143623.947[Thread-3] INFO [DataSourceManager:19] Closed
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);
}
我的开放式和封闭式方法是这样的
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()
作为日志中连接的唯一名称。但是我想知道是否有更好的方法可以做到这一点。只需在对象
超类上使用默认的toString()
实现即可
它已经为您做到了这一点:
getClass().getName() + '@' + Integer.toHexString(hashCode())
toHexString(hashCode())
将在此处为您提供唯一的id。JVM保证它是唯一的值。您要打印哪个对象?似乎您试图打印的类没有覆盖toString()
。我不想打印任何对象。我只想显示我已打开或关闭的连接对象的名称。如果您发布代码..您正在尝试打印一个对象:连接。连接是一个对象。但是一个连接没有名称。@jbnize如果那个帮助我也在计划这次访问,请不要添加代码段,然后我阅读了这个文档,根据这个源代码,hashCode不必对每个对象都是唯一的。这就是我必须寻找其他选项的地方。@RajaAnbazhagan同时打开的两个连接的两个hashCode()
s相同的可能性几乎为零。如果您想让它完全独一无二,可以执行类似于hashCode()+'-'+System.nanoTime()
的操作。在日志中进行企业级jdbc调试时,我可以使用hashCode()
作为唯一的id。最后,我决定使用hashCode的hextstring方法。