好吧,这是我的疑问......
我有一个 blazeDS (tomcat) 应用程序,其中包含一些类,每个类都使用 Config
和 DB
类进行配置和数据库连接...
这是一个示例
配置
类
public class Config {
public static final String DBClass = "oracle.jdbc.driver.OracleDriver";
public static final String ConnectString = "jdbc:oracle:thin:@//127.0.0.1:1521/xe";
public static final String UserDB = "user";
public static final String PasswordDB = "pass";
}
数据库
类
public class DB
{
public DB() {}
public static Connection dbConnect(Connection c)
{
try
{ if (c == null || c.isClosed()){
Class.forName(Config.DBClass);
c = DriverManager.getConnection(Config.ConnectString,Config.UserDB,Config.PasswordDB);
}
return c;
}
catch (Exception e)
{
System.out.println(e.getMessage());
return null;
}
}
public static void closeConnection(Connection connection) throws SQLException
{
if (!connection.isClosed())
connection.close();
}
}
我有一个测试和生产环境,每个数据库访问都有不同的用户/密码。 我注意到,当使用测试类更新生产文件时(我不覆盖 Config.class ),我从数据库收到错误...
那么,编译版本中的静态最终
值(用户/密码)是否直接保存在类本身中(在我的例子中是DB.class)???
最佳答案
简而言之,是的。
摘自Java specs :
"References to fields that are constant variables (§4.12.4) are resolved at compile-time to the constant value that is denoted. No reference to such a field should be present in the code in a binary file (except in the class or interface containing the field, which will have code to initialize it). Such a field must always appear to have been initialized (§12.4.2); the default initial value for the type of such a field must never be observed. See §13.4.9 for a discussion." (p. 339)
关于java - Java中声明静态常量会影响编译后的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736580/